Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 5 of 10
useState - State & Reactivity
useState is where React data lives. But it's more nuanced than it appears - state updates are asynchronous and batched, state is a snapshot per render, and knowing WHAT to put in state (versus deriving it) is a skill that separates juniors from seniors.
useState - The State Snapshot Model
import { useState } from 'react';
// useState returns [currentValue, setter]
// The SETTER schedules a re-render; it does NOT mutate the current value
function Counter() {
const [count, setCount] = useState(0); // initial value = 0
function handleClick() {
// โ WRONG - reads stale 'count' snapshot (count is 0 here)
setCount(count + 1); // schedules render with count=1
setCount(count + 1); // ALSO schedules render with count=1 (not 2!)
// React batches these: result is count=1, not count=2
// โ
CORRECT - functional updater reads the LATEST queued state
setCount(prev => prev + 1); // +1
setCount(prev => prev + 1); // +2 (reads result of previous updater)
// Result: count=2 โ
}
return <button onClick={handleClick}>Count: {count}</button>;
}
// Lazy initial state - pass a FUNCTION for expensive initial computation
// Without lazy: runs initializer on EVERY render (wasted)
const [data, setData] = useState(expensiveInit()); // โ called every render
// With lazy: runs initializer only ONCE (on mount)
const [data, setData] = useState(() => expensiveInit()); // โ
State vs Derived State - What Goes in useState
// Rule: If a value can be COMPUTED from existing state/props, DON'T put it in state
// โ BAD - redundant derived state (causes double re-renders)
function Cart({ items }: { items: CartItem[] }) {
const [totalPrice, setTotalPrice] = useState(0); // โ derived!
// Now you must manually keep totalPrice in sync - a recipe for bugs
useEffect(() => {
setTotalPrice(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);
return <div>Total: ${totalPrice}</div>;
}
// โ
GOOD - compute directly during render (no extra state, no sync bug)
function Cart({ items }: { items: CartItem[] }) {
const totalPrice = items.reduce((sum, item) => sum + item.price, 0);
return <div>Total: ${totalPrice}</div>;
}
// What SHOULD be in state:
// โ
Data that changes over time and triggers UI updates
// โ
User input values (form fields)
// โ
Toggle flags (isOpen, isLoading, isAuthenticated)
// โ
Selected item ID (not the full item - derive the item from the ID)
// โ
Server data after it's fetched (or use TanStack Query)
// What should NOT be in state:
// โ Values derivable from state/props (compute them)
// โ Values that don't affect rendering (use useRef instead)
// โ Duplicates of props (sync bugs guaranteed)Updating Objects & Arrays in State
// State must be treated as IMMUTABLE - never mutate directly
// โ WRONG - mutates state directly
const [user, setUser] = useState({ name: 'Alice', age: 30 });
user.age = 31; // โ mutates existing object
setUser(user); // โ same reference - React skips re-render
// โ
CORRECT - create a new object with spread
setUser(prev => ({ ...prev, age: 31 }));
// Arrays - same principle: create new arrays
const [todos, setTodos] = useState<Todo[]>([]);
// Add item
setTodos(prev => [...prev, newTodo]);
// Remove item
setTodos(prev => prev.filter(todo => todo.id !== idToRemove));
// Update item
setTodos(prev =>
prev.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
)
);
// Complex nested state - consider useImmer or restructuring
// Use immer for deeply nested updates:
import { useImmer } from 'use-immer';
const [state, updateState] = useImmer({ user: { address: { city: 'NY' } } });
updateState(draft => {
draft.user.address.city = 'SF'; // โ
immer handles immutability internally
});React 18 Automatic Batching
// Before React 18: batching only happened inside React event handlers
// After React 18: ALL updates are automatically batched (setTimeout, Promises, etc.)
// React 18 - these three setStates cause ONE re-render (batched)
setTimeout(() => {
setCount(c => c + 1);
setFlag(f => !f);
setName('Alice');
// โ ONE re-render, not three
}, 1000);
fetch('/api/data').then(() => {
setCount(c => c + 1);
setItems([...items, newItem]);
// โ ONE re-render (React 18 batches inside Promises too)
});
// To opt OUT of batching (rare - usually wrong):
import { flushSync } from 'react-dom';
flushSync(() => setCount(c => c + 1)); // forces synchronous re-render
flushSync(() => setFlag(f => !f)); // another synchronous re-renderCommon Mistakes - useState
- Reading state immediately after calling setState - setState is async; the state variable won't reflect the update until the next render
- Mutating arrays/objects directly - `items.push(x); setItems(items)` - React sees same reference and skips the re-render entirely
- Storing derived state - causes double renders, stale data bugs, and unnecessary complexity; compute values during render instead
- Initializing state from props directly (`useState(props.data)`) - the state only uses the prop as the INITIAL value; future prop changes are ignored. Use `useEffect` or make it fully controlled
- State that should be a ref - if a value changes but shouldn't cause a re-render (e.g. tracking a timer ID, storing a scroll position), use `useRef` instead of `useState`
Tip
Tip
Practice useState State Reactivity in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for useState - State & Reactivity
Practice Task
Note
Practice Task - (1) Write a working example of useState State Reactivity from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with useState State Reactivity is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- useState is where React data lives.
- Reading state immediately after calling setState - setState is async; the state variable won't reflect the update until the next render
- Mutating arrays/objects directly - `items.push(x); setItems(items)` - React sees same reference and skips the re-render entirely
- Storing derived state - causes double renders, stale data bugs, and unnecessary complexity; compute values during render instead
Finished this lesson?