hardFrontend

Why must React state updates be immutable?

601 views
01

Understand the problem

How reference equality drives bailouts and concurrent correctness.

reactstateimmutability
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Explore the playground snippets

New reference vs. in-place mutation
Run Playground
import { useState } from 'react';

export default function App() {
  const [todos, setTodos] = useState([{ id: 1, text: 'Learn immutability' }]);
  const [text, setText] = useState('');

  function addCorrect() {
    if (!text.trim()) return;
    setTodos((prev) => [...prev, { id: Date.now(), text }]); // NEW array -> re-renders
    setText('');
  }
  function addBroken() {
    todos.push({ id: Date.now(), text: text || 'mutated' }); // same reference -> no re-render
    setText('');
  }

  return (
    <div style={{ fontFamily: 'sans-serif', padding: 24 }}>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <button onClick={addCorrect}>Add (immutable)</button>{' '}
      <button onClick={addBroken}>Add (mutate — UI won't update)</button>
      <ul>{todos.map((t) => <li key={t.id}>{t.text}</li>)}</ul>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.