Managing Component State with useState
Quick Answer: useState is a React Hook that gives a component its own memory and tells React to re-render the screen whenever data changes. Always replace state with a new immutable copy and use functional updates (prev => ...) when the next value depends on the previous one.
Imagine Lakshmi runs a busy morning tiffin delivery app in Chennai. At 8:15 AM, Arjun opens the app to order hot idlis.
Arjun taps the + button to order 3 plates, switches on the "Extra Sambar" toggle, and types his T. Nagar delivery address. Every single tap must update the screen immediately.
Why does a normal JavaScript variable fail here, and how does useState keep the UI in sync?
1. Why Plain Variables Fail in React
The problem without useState
In a regular React function component, local variables do not survive between renders, and changing them never notifies React to repaint the screen.
Example 1: Why a plain JavaScript variable breaks Arjun's cart
Clicking the button changes the variable in memory, but the screen stays stuck at 1.
function IdliCounter() {
let plates = 1;
function addPlate() {
plates = plates + 1; // Changes memory, but React does NOT re-render!
console.log(plates);
}
return <button onClick={addPlate}>Plates: {plates}</button>;
}
What happens when Arjun clicks 3 times
Console logs: 2, 3, 4 Screen still shows: Plates: 1
- Changing a local variable does not trigger a React re-render.
- If the component re-renders for any other reason,
let plates = 1resets back to 1. - Users see stale numbers and think Lakshmi's app is frozen.
The solution: The useState Hook
State = a component's private memory that React preserves across re-renders.
useState returns a pair of values: the current state value and a setter function that schedules a re-render.
Live Cycle: How useState Updates Arjun's Tiffin Order
Watch how each interaction creates a fresh immutable state object and triggers a clean React re-render.
React compares the old and new state using Object.is(). Creating a new object with spread syntax (...prev) guarantees React sees the change and updates the screen.
2. Counters, Toggles, and Interactive Forms in Practice
Controlled Input = a form field whose value is driven directly by React state via value and onChange.
Here is how Lakshmi's tiffin app combines a counter, a boolean toggle, and a controlled text input in one clean component.
Example 2: Complete Tiffin Order Form using useState
Notice how every update uses a functional updater and never mutates the existing object.
import { useState } from 'react';
export default function TiffinOrderForm() {
const [order, setOrder] = useState({
plates: 1,
extraSambar: false,
area: 'Adyar'
});
// 1. Counter with functional update
function addPlate() {
setOrder(prev => ({ ...prev, plates: prev.plates + 1 }));
}
// 2. Boolean toggle
function toggleSambar() {
setOrder(prev => ({ ...prev, extraSambar: !prev.extraSambar }));
}
// 3. Controlled form input
function handleAreaChange(e) {
const nextArea = e.target.value;
setOrder(prev => ({ ...prev, area: nextArea }));
}
return (
<div>
<button onClick={addPlate}>Plates: {order.plates}</button>
<button onClick={toggleSambar}>
Extra Sambar: {order.extraSambar ? 'ON' : 'OFF'}
</button>
<input value={order.area} onChange={handleAreaChange} />
</div>
);
}
Why functional updates matter (State Batching)
React batches multiple setState calls inside one event handler to avoid wasted renders. If you write setPlates(plates + 1) twice in a row, both calls read the same stale plates value from the current render.
Passing an updater function like setPlates(prev => prev + 1) tells React to queue each step using the latest pending state, so calling it twice correctly adds 2.
Lazy Initialization for Heavy Defaults
If your initial state requires expensive work (like reading from localStorage), pass a function to useState so it runs only once on the first render:
// Runs only on initial mount, not on every re-render
const [cart, setCart] = useState(() => JSON.parse(localStorage.getItem('cart') || '[]'));
3. Direct Mutation vs. Immutable State Updates
| Direct Mutation (Broken) | Immutable Update (Correct) |
|---|---|
order.plates = 2; setOrder(order); |
setOrder(prev => ({ ...prev, plates: 2 })); |
items.push('Vada'); setItems(items); |
setItems(prev => [...prev, 'Vada']); |
| Same memory reference → React skips re-render. | New memory reference → React updates the UI. |
The important terms to remember
- Immutability = never editing existing state objects or arrays in place; always creating a new copy.
- Functional Update = passing
prev => nextValueto a setter so updates never read stale state. - State Batching = grouping multiple state updates inside one event into a single re-render.
- Controlled Component = a form element whose value is controlled by React state.
Design tip: Keep state as flat and minimal as possible. If you can calculate a value during render (like const total = order.plates * 40), compute it directly instead of storing it in another useState.
4. Common Mistakes to Avoid
1. Logging state immediately after calling the setter
Calling setPlates(plates + 1) schedules the next render. It does not change plates in the currently running function, so console.log(plates) still prints the old number.
Better approach: Store the next value in a local variable (const next = plates + 1) if you need to log or send it right away.
2. Calling useState inside an if statement or loop
React tracks Hooks by the exact order they are called on every render. Putting useState inside a condition breaks that order and crashes the component.
Better approach: Always call useState at the very top level of your React function component.
3. Mutating arrays with .push() or .splice()
Methods like .push() modify the existing array in place without creating a new reference, so React ignores the update.
Better approach: Use non-mutating methods: spread [...arr, item] to add, .filter() to remove, and .map() to update.
5. Interview Questions & Practice
Question 1: Why does React require immutable state updates?
What the interviewer expects: Understanding of shallow reference comparison (Object.is) and predictable rendering.
Strong answer: "React checks whether state changed by comparing the old and new references using Object.is(). If I mutate Arjun's order object in place, the reference stays identical, so React assumes nothing changed and skips the re-render. Returning a new copy with the spread operator gives React a new reference and keeps previous render snapshots safe."
Question 2: When should you use a functional state update instead of passing a direct value?
What the interviewer expects: Knowledge of state batching and stale closures.
Strong answer: "Whenever the next state depends on the previous state, like incrementing Arjun's idli plate counter or toggling extra sambar. Because React batches updates, calling setPlates(plates + 1) twice reads the same stale value. Using setPlates(prev => prev + 1) guarantees every queued update runs on the latest value."
What interviewers expect at different levels
- Junior developer: Knows how to declare
useState, wire up a controlled input, and avoid mutating arrays directly. - Senior developer: Explains state batching, stale closures, lazy initializers, and when to derive values instead of duplicating state.
- Technical architect: Knows when to lift state up, split state for fewer re-renders, or move from
useStatetouseReduceror external stores.
Beginner: Hospital appointment toggle
Create a SlotCard component with a boolean isBooked state. Clicking the button should toggle between "Available" and "Booked".
Expected result: Uses setIsBooked(prev => !prev) and updates the button label on every click.
Intermediate: UPI quick-transfer form
Build a single-object form state holding upiId, amount, and note. Add a "Reset Form" button that clears all three fields immutably.
Hint: Use computed property names like setForm(prev => ({ ...prev, [e.target.name]: e.target.value })).
Advanced: Festival cart with nested item updates
Manage an array of cart items where each item has id, name, and qty. Implement immutable handlers for adding an item, removing an item, and incrementing one item's quantity.
- Use
.map()with object spread to incrementqtyfor a matchingid. - Use
.filter()to remove an item when its quantity hits 0.
Challenge: Compute the grand total during render without creating a separate total state variable.
6. Next Steps
- Previous Article: Setting Up a Modern React Project with Vite
- Next Article: Handling Side Effects & Data Fetching with useEffect
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.