useState is a fundamental React Hook that allows function components to store values between renders and update the UI when those values change.
useState?useState returns an array containing the current state and a setter function.
const [state, setState] = useState(initialValue);
Example:
function Counter() {const [count, setCount] = useState(0);return (<button onClick={() => setCount(count + 1)}>Count: {count}</button>);}
When the button is clicked, React updates count and re-renders the component.
When the next state depends on the previous state, use a functional update to ensure React calculates the new value from the previous state.
setCount((prev) => prev + 1);
This is especially useful when performing multiple updates in the same event handler.
setCount((prev) => prev + 1);setCount((prev) => prev + 1);setCount((prev) => prev + 1);
React processes these updates in sequence, increasing the count by three.
React state should be treated as immutable. Create new objects or arrays instead of modifying existing state directly.
Objects:
const [user, setUser] = useState({ name: "Daniel" });setUser((prev) => ({...prev,name: "Alex",}));
Arrays:
const [items, setItems] = useState<string[]>([]);setItems((prev) => [...prev, "React"]);
Creating new references allows React to detect state changes correctly.
If computing the initial state is expensive, pass a function to useState instead of calculating the value on every render.
const [value, setValue] = useState(() => computeInitial());
React uses the function’s return value to initialize the state. The initializer may run twice in development Strict Mode, so it should be pure.
Keep state in the component that needs it whenever possible. This reduces unnecessary state sharing and keeps components easier to maintain.
function SearchInput() {const [query, setQuery] = useState("");return (<inputvalue={query}onChange={(e) => setQuery(e.target.value)}placeholder="Search..."/>);}
When multiple components need the same state, move it to their closest common parent and pass the value and update function through props.
function App() {const [query, setQuery] = useState("");return (<><SearchInput query={query} onChange={setQuery} /><SearchResults query={query} /></>);}
Now both components share the same source of truth.