Changing state directly
Short answer
State cannot be changed directly because React will not find out that you changed it. Which means no re-render will happen.
Example
Wrong:
function Counter() {
const [count, setCount] = useState(0);
function increment() {
count = count + 1; // changing the value directly
}
return <button onClick={increment}>{count}</button>;
}Correct:
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1); // using setCount
}
return <button onClick={increment}>{count}</button>;
}In the first case React will not re-render the component, in the second - it will, because React now knows the UI needs to update.
Why this happens
1. React does not track variables directly
React does not use "reactivity" the way Vue or Svelte does. It is not "subscribed" to variables and does not track their changes.
useState creates an internal state entry in React (in the Fiber tree).
When you call setState, React:
- stores the new value in its internal structure,
- marks the component as "needing an update",
- triggers a re-render.
If you simply do count++, React will not find out about the change -
because you only changed a local variable,
not what React stores inside itself.
2. A direct mutation breaks immutability
React expects state to be immutable. When you change it directly, React cannot compare "before / after".
Example with an object: Bad:
setUser(user.name = "Timur");Good:
setUser({ ...user, name: "Timur" });Why? On re-render React compares the old object and the new one (via a shallow comparison). If the reference changed - the data is new → the UI needs to update. If the reference is the same - React decides that nothing changed.
3. A direct mutation breaks predictability
React optimizes updates and may batch them, and if you mutate state manually, these optimizations break - the UI can end up in an inconsistent state.
Summary
| Reason | Explanation |
|---|---|
| React does not track variables | It learns about a change only through setState() |
| Broken immutability | A direct mutation breaks the comparison of old and new state |
| Lost predictability | React cannot safely optimize updates |
| No re-render | The UI will not update, even if the data changed |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.