useState
Subject: React
π What is useState
?
useState
is a Hook in React that lets you add state (i.e., memory/variables) to functional components.
Before Hooks, only class components could hold state using this.state
. Now, functional components can hold and update state too β thanks to useState
.
π¦ Syntax
Part | Meaning |
---|---|
stateVariable | Current value of the state |
setStateFunction | Function to update that state |
useState(value) | Initializes state with given initial value |
β Example: Counter App
π Whatβs Happening:
useState(0)
initializescount
with 0setCount(count + 1)
updates the value- React re-renders the component with the new
count
π§ Logic Behind the Scenes
React keeps track of count
and automatically updates the DOM when setCount()
is called.
β Another Example: Input Field (Form)
π Explanation:
name
stores the input valuesetName()
updates it when typing- React shows: βHello, {name}β in real time
π Important Rules for useState
β Rule | π Why It Matters |
---|---|
Donβt mutate state directly | Use setState() instead of modifying variable |
State updates are async | Donβt expect immediate changes after setting state |
Can use multiple useState s | Separate states for different variables |
β Multiple State Variables
Or using an object:
β οΈ Common Mistakes
Mistake | Fix |
---|---|
count++ | Use setCount(count + 1) |
Forgot to import useState | import { useState } from 'react' |
Modify state object directly | Use spread: { ...oldState, key: v } |
π§ Best Practice: Functional Updates
Use when updating state based on the previous value:
Helps avoid bugs with async updates or inside loops.
π Summary
Feature | Description |
---|---|
useState() | Initializes state in a functional component |
setState function | Updates the value and triggers re-render |
Re-renders UI | React auto-updates DOM when state changes |
Use Cases | Forms, toggles, counters, filters, etc. |
Advertisement Slot 1
Advertisement Slot 2