useState
is a native state management hook in React that allows components to keep track of state between renders.
Logical Breakdown of useState
:
-
Define the initial state:
-
useState(10)
→ Initializes a number. -
useState("")
→ Initializes an empty string. -
useState(() => "Jack")
→ Uses a lazy initialization function.
-
-
Destructure the returned array:
-
useState
returns an array with two values:- The current state value
- A function to update the state
-
Example:
const [name, setName] = useState("");
-
-
Update state using the setter function (
setState
)- Directly modifying the state variable won't trigger a re-render.
-
Always use the setter function to update state:
setName("Alice"); // Correct name = "Alice"; // Won't update state
Why use setState
instead of modifying the variable?
-
For primitive data types (numbers, strings, booleans):
- Changing the variable only creates a local copy. React won’t recognize the change*.*
-
For reference types (arrays, objects):
- Modifying the variable directly mutates the original state, which React might not track.
- Best practice is to spread the existing state and then update it.
Updating an Array in State (Best Practice)
const [items, setItems] = useState(["Apple", "Banana"]);
// Incorrect(Direct mutation)
items.push("Orange");
setItems(items);
// Correct (Create a new array)
setItems([...items, "Orange"]);
Updating an Object in State (Best Practice)
const [user, setUser] = useState({ name: "Jack", age: 25 });
// Incorrect (Direct mutation)
user.name = "Alice";
setUser(user);
// Correct (Create a new object)
setUser({ ...user, name: "Alice" });
Top comments (0)