Skip to main content

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:

javascript
function Counter() { const [count, setCount] = useState(0); function increment() { count = count + 1; // changing the value directly } return <button onClick={increment}>{count}</button>; }

Correct:

javascript
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:

javascript
setUser(user.name = "Timur");

Good:

javascript
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

ReasonExplanation
React does not track variablesIt learns about a change only through setState()
Broken immutabilityA direct mutation breaks the comparison of old and new state
Lost predictabilityReact cannot safely optimize updates
No re-renderThe UI will not update, even if the data changed

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.