Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 132 ยท Practice and Review

Common React Mistakes and How to Fix Them

Ten React mistakes every developer makes - missing keys, mutated state, stale closures, effect misuse, conditional hooks, controlled inputs and hydration - each with the real error and the fix.

Every React developer makes the same mistakes. They are not signs of a weak programmer; they follow from how React works, and once you recognize the pattern you can fix each one in a minute. This lesson takes ten of the most common bugs and turns each into a short example you can run. Where React prints a warning or an error, the text you see below is the real message from the React 19.3 development build that powers our editor, so you will recognize it when it shows up in your own console.

Each section follows the same four steps: the broken code, what actually happens, why, and the fix. Examples whose title ends with "(fails on purpose)" are meant to produce an error or a warning. Open the console panel under the preview to read it.

Warnings like these come from React's development build. A production build skips most of the checks to stay small and fast, which is one more reason to fix warnings while you are developing instead of ignoring them.

Mistake 1: lists without keys

React needs a way to tell which list item is which between renders. You provide that with a key. Forgetting it is the first warning most beginners see.

A list without keys (fails on purpose)

The list still renders, and the console prints: Each child in a list should have a unique "key" prop. (followed by a link to the React documentation). The warning is about correctness, not looks: without keys React falls back to matching items by position, which is fine for a static list and wrong as soon as items are added, removed or reordered.

The fix is a stable, unique key that belongs to the data: <li key={name}> here, or key={user.id} for real records. A key must be unique only among siblings, and it must not change between renders.

The bigger bug: index keys

The tempting fix is key={index}. That silences the warning and creates a worse bug the moment the list can change. The key is the item's identity. If the identity is "the first row", then after you remove the first item the old first row's state (what you typed in an input, which checkbox is ticked) is handed to the item that moved up. Type something into the first box of each list, then press "Remove first" in both lists:

Index keys versus id keys

Type "hello" into the Apple input of each list and remove the first item. In the index-key list the text "hello" is still on screen, now sitting next to Banana. In the id-key list it disappears together with Apple, which is correct. Use an index as a key only for lists that are static, never reordered and never filtered. More in lists and keys.

Mistake 2: mutating state

State updates only happen when you give React a new value. React compares the old and new state with Object.is; if they are the same object, it assumes nothing changed.

Mutating state versus copying it

Click "Push (mutation)" first. The console says the array has two items, but the screen still shows only milk: setItems(items) passed the same array object, so React skipped the render. The data changed behind React's back. The next successful render (try "Spread (copy)") suddenly shows eggs too, which makes the bug look random.

The fix is to treat state as read-only and build a new value: [...items, x], items.filter(...), items.map(...), { ...object, field: value }. See objects and arrays in state. Watch out for sort, reverse and splice, which also mutate; copy first ([...items].sort() or items.toSorted()).

Mistake 3: the stale closure

Every render has its own copy of your variables. A function created during a render sees the values from that render, forever, even if it runs later.

Stale value in a delayed update

Click "Add later (wrong)" twice quickly and wait: the count becomes 1, not 2. Both clicks created a timeout that captured count as 0, so both set 0 + 1. Do the same with the right button and you get 2, because (current) => current + 1 asks React for the latest value at the moment it runs. The updater function is the cure for stale state in timers, promises and event listeners (state updates). When an Effect would otherwise capture stale values, see useEffectEvent and effect dependencies.

Mistake 4: unstable Effect dependencies

An Effect re-runs when any dependency changes, and React compares them with Object.is. An object, array or function written inside the component body is a new value on every render, so it always "changed".

An object dependency restarts the Effect

Click the button a few times. Each click logs disconnect then connect with blue, even though nothing about the channel changed. With a real subscription or connection that is wasted work and sometimes visible flicker. The fix is to depend on primitive values ([color]), to create the object inside the Effect, or, if an object really must be shared, to keep it stable with useMemo.

A worse cousin is an Effect that sets state and has no dependency array, or depends on the value it just set. That is a render loop: set state, render, Effect runs, set state again. React stops runaway loops of this kind and complains in the console, but the page is already stuck. If your Effect only computes something from props and state, delete it and compute the value during render (you might not need an Effect).

Mistake 5: calling hooks conditionally

React identifies each hook by the order in which it is called during a render. Skip one on some renders and the order no longer matches.

A hook inside an if (fails on purpose)

The first render works. After you press the button the console reports React has detected a change in the order of Hooks called by the component and then an error, Rendered more hooks than during the previous render. Because nothing catches it, the whole tree disappears.

The fix is to call every hook at the top level, in the same order, always. Put the condition inside the hook's use, or move the conditional part into a child component that is rendered conditionally:

JSX
function App() {
  const [expanded, setExpanded] = useState(false);
  const [name] = useState('Ada');
  return (
    <>
      <button type="button" onClick={() => setExpanded(true)}>Hello {name}</button>
      {expanded && <Details />}
    </>
  );
}

The same rule rules out hooks after an early return, inside loops, and inside nested functions. The ESLint plugin catches these before you run anything (rules of Hooks).

Mistake 6: switching an input from uncontrolled to controlled

A controlled input gets its value from state. If the state starts as undefined, the input begins its life as uncontrolled (the browser owns the text), and when state later becomes a string, React has to switch modes.

value starts undefined (fails on purpose)

Type a letter. The console prints A component is changing an uncontrolled input to be controlled. and adds that this is likely caused by the value changing from undefined to a defined value. The same warning appears for the opposite switch (null/undefined after typing, for example when you reset state to undefined).

The fix is to start with a real value: useState(''). For data loaded later, use an empty-string fallback: value={user.name ?? ''}. Choose one style, controlled or uncontrolled, for the whole life of the input (controlled and uncontrolled).

Mistake 7: calling the handler instead of passing it

onClick={handleClick} hands React a function to call later. onClick={handleClick()} calls it now, during rendering, and passes whatever it returned.

Calling the setter during render (fails on purpose)

setN(n + 1) runs on every render, each call schedules another render, and React gives up with: Too many re-renders. React limits the number of renders to prevent an infinite loop. The fix is to pass a function:

JSX
<button type="button" onClick={() => setN(n + 1)}>n = {n}</button>

If the handler needs arguments, wrap it in an arrow function: onClick={() => remove(item.id)}, never onClick={remove(item.id)}. The same applies to anything you pass as a callback prop (events).

Mistake 8: defining a component inside another component

A function declared inside a component body is created again on every render. React compares component types to decide whether to keep or rebuild a subtree, and a new function is a new type, so React throws the old subtree away and mounts a fresh one, losing all its state and focus.

Components defined inside components

Type something into both inputs and press the button. The text in the "inside" field vanishes (the input was remounted), while the "outside" one keeps its text. The fix is simple: declare every component at the top level of the module, and pass data in through props (components).

Mistake 9: copying props into state

useState(props.value) uses the prop only for the first render. After that React ignores it, so the state does not follow later changes. The component looks correct until the parent changes the prop.

State that ignores new props

After pressing "Switch name" the direct line says Grace while the copied one still says Ada. If the value is just displayed or calculated from the prop, use the prop directly or derive from it during render. If you really want an editable draft that starts from the prop, name it that way (initialName) and reset it with a key when the identity changes: <Editor key={user.id} initialName={user.name} /> (choosing state structure).

Mistake 10: output that differs between server and browser

With server rendering the server produces HTML first, and then React "hydrates" it in the browser by attaching event handlers. For that to work, the first browser render must produce exactly the markup the server sent. Anything that differs, such as Date.now(), Math.random(), or branching on typeof window, causes a hydration mismatch.

The editor can reproduce this because react-dom/server runs in the browser: the example creates server-style HTML with renderToString, then hydrates it with a component that renders different text.

Hydration mismatch (fails on purpose)

The page ends up showing "Rendered on the client", and the console logs: Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. React recovers by throwing away the server HTML for that part of the tree and rendering it again, so users still see a working page, but you lose the speed benefit of server rendering and might see a flash of content.

Fix it by making the first client render match the server. Values that only exist in the browser (the current time, window.innerWidth, anything from localStorage) should be read in an Effect after hydration, so the first render uses a fixed placeholder; and random values or ids should come from useId or be passed in as props from the server (SSR and hydration).

A short debugging checklist

When something behaves strangely, check these in order:

  1. Read the first console message. React's wording is usually precise, and the first error causes the later ones.
  2. Is this a rendering or an interaction problem? If it happens on load, look at render code; if it happens after a click, look at the handler and what state it sets.
  3. Did you change the value, or a copy? Mutation and stale closures account for a large share of "my state is wrong" questions.
  4. Are all hooks at the top level, in a fixed order?
  5. Is each Effect justified and complete? Does it synchronize with something outside React, list all dependencies, and clean up?
  6. Turn on <StrictMode>. It deliberately runs renders and Effects twice in development to expose impure code.
  7. Use React DevTools to inspect props, state and which component rendered (debugging React).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A list uses key={index}. What goes wrong when the first item is removed?

    Keys are identities. With index keys the second item becomes 'item 0', so React reuses the first row's DOM node and state for it. Use a stable id from the data.
  2. 2. Why does setItems(items) after items.push(x) not update the screen?

    React compares state with Object.is. A mutated array keeps its identity. Build a new array with spread, filter or map.
  3. 3. Two quick clicks on a button that runs setTimeout(() => setCount(count + 1), 100) leave count at 1. Which change fixes it?

    Both timeouts captured the same count from their render. The updater form receives the latest state when it runs.
  4. 4. What does React do when an Effect lists an object created in the component body as a dependency?

    Dependencies are compared by reference with Object.is. A fresh object each render is always different. Depend on primitive values, create the object inside the Effect, or memoize it.
  5. 5. Which line causes the 'Too many re-renders' error?

    setN(n + 1) without an arrow function runs during rendering, schedules another render, and so on. The other forms pass a function that is called only on click.

Summary

  • Give every list item a stable, unique key from the data; index keys are only safe for static lists.
  • Never mutate state or props: create new arrays and objects, and copy before sort or reverse.
  • Use updater functions (setX((x) => ...)) when a later update depends on the latest value, as in timers and promises.
  • Keep Effect dependencies stable and complete; create objects inside the Effect or depend on primitives.
  • Call hooks unconditionally at the top level, in the same order every render.
  • Initialize inputs with real values (''), pass handler functions instead of calling them, and define components at module level.
  • Do not copy props into state unless you want a draft, and make the first client render match the server HTML.

Next: Practice Problems: Components, Props and State