Topic 16 of 54
The useState Hook
Overview
`useState` is the most important and frequently used Hook in React. It allows you to add state variables to functional components. It returns an array with exactly two items: the current state value, and a setter function to update that value.
Syntax
Never modify `count` directly (`count = 5`). Always use `setCount(5)`. Calling the setter function tells React: 'Hey, this data changed, please re-render the screen'.
Basic useState Syntax
jsx
import { useState } from 'react';
function Counter() {
// Destructuring the array returned by useState
// [currentValue, setterFunction] = useState(initialValue)
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
{/* Call the setter function to update state */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}When your new state depends on the old state (like adding 1 to the current count), always pass a callback function to the setter: `setCount(prev => prev + 1)`.
The Safe Way
jsx
function SafeCounter() {
const [count, setCount] = useState(0);
const incrementTwice = () => {
// ❌ BAD: Might use stale state if batched
// setCount(count + 1);
// setCount(count + 1);
// ✅ GOOD: Pass a function to get the guaranteed latest previous state
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
};
return <button onClick={incrementTwice}>Add 2</button>;
}Common Pitfalls
- Mutating state directly (e.g., `count++`). This will not trigger a re-render and causes massive bugs.
- Calling hooks conditionally (inside `if` statements or loops). Hooks must be called at the top level of the component.
Interview Tips
- Always explain Functional Updates (`prev => prev + 1`). Interviewers look for this to verify you understand that React state updates are asynchronous and can be batched.
Real-World Example
Managing a simple text input.
example
jsx
function LiveInput() {
const [text, setText] = useState("");
return (
<div>
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type here..."
/>
<p>You typed: {text}</p>
</div>
);
}