Bug: useState not updating the UI
Error message
State appears to update but the UI doesn't change
Quick summary
You mutated state directly instead of calling the setter with a new value, so React didn't detect the change and didn't re-render.
Why this happens
Mutated state directly:
state.items.push(newItem)instead of creating a new arrayMutated an object property:
state.user.name = 'new'instead of creating a new objectPassed the same reference to setState:
setState(state)Used
==instead of===in a comparison that controls rendering
Minimal example
const [items, setItems] = useState([]);
items.push(newItem); // Direct mutation!
setItems(items); // Same reference, no re-renderconst [items, setItems] = useState([]);
setItems([...items, newItem]); // New array referenceReact compares the new state reference to the old one. Spreading creates a new array, so React detects the change and re-renders.
How to diagnose
Check if you're creating new objects/arrays or mutating existing ones
Log the state before and after to see if the reference changed
Use React DevTools to inspect state updates
How to fix
Create a new array:
setItems([...items, newItem])Create a new object:
setUser({ ...user, name: 'new' })Use the updater function form:
setItems(prev => [...prev, newItem])
How to prevent
Never mutate state directly — always create new objects/arrays
Use immutable data libraries (Immer) for complex state
Enable ESLint no-param-reassign rule