Beginner LevelReact JS & React 19
How does the useState hook work and what is functional updater syntax?
❓ Interview Prompt: Explain useState initialization, state updates, batching, and when to use functional updates.
'useState' declares a state variable that persists across re-renders.
Syntax:
'const [state, setState] = useState(initialValue);'
Key Mechanics:
1
Asynchronous Updates & Batching: Calling 'setState' does not change the state variable immediately in the current execution scope. React schedules a re-render and batches multiple state updates together for performance.
2
Functional Updater Syntax: When new state depends on the previous state, pass a function to the setter: 'setCount(prev => prev + 1)'. This ensures you are working with the most up-to-date state inside batched updates.
3
Lazy Initialization: If initial state requires an expensive calculation, pass an initializer function: 'useState(() => computeExpensiveValue())' so it only runs on mount.
Code Implementation Example
jsx
function Scoreboard() {
const [score, setScore] = useState(0);
const handleBadIncrement = () => {
// ❌ Stale state bug due to batching!
setScore(score + 1);
setScore(score + 1); // Both use same 'score' snapshot
};
const handleGoodIncrement = () => {
// ✅ Functional updater uses exact previous state
setScore(prev => prev + 1);
setScore(prev => prev + 1);
};
// Lazy initialization (runs only once on mount)
const [data, setData] = useState(() => JSON.parse(localStorage.getItem('cache') || '{}'));
}💡Functional updates preventing stale state bugs during React batching.
🎯 Interview Key Takeaway
Always use functional updater syntax setX(prev => ...) when new state depends on the previous state value.
#useState#Hooks#Batching#Beginner
Back to all React JS & React 19 Questions→