React ยท Chapter 12 of 42
useState Hook
`useState` is the fundamental hook for adding state to function components. It returns an array with the current value and a function to update it.
You can call `useState` multiple times in one component to manage multiple independent pieces of state.
Basic usage
`const [value, setValue] = useState(initialValue);` โ the initial value is only used on the first render.
Functional updates
When new state depends on old state, pass a function: `setCount(prev => prev + 1)` to avoid stale-state bugs.
Example 1 (jsx)
import { useState } from "react";
function Toggle() {
const [on, setOn] = useState(false);
return (
<button onClick={() => setOn(prev => !prev)}>
{on ? "ON" : "OFF"}
</button>
);
}Output
OFF (toggles to ON on click)The functional update form safely flips the boolean state.
Key points
- useState adds local state to function components.
- It returns [value, setter] via array destructuring.
- Use a function updater when new state depends on previous state.
- Multiple useState calls manage independent state values.
๐ก Note: Hooks must be called at the top level of a component, never inside loops or conditions.
