completefrontend

Common React mistakes beginners make

Beginners trip over the same few React mistakes: changing state directly, a stray 0 from &&, index keys, and effects that never clean up. Here's what each one looks like, why it happens, and the fix.

Two mistakes in red, each with its fix in green: onClick={save()} becomes onClick={save}, and items.length && becomes items.length > 0 &&

When you learn chess, you lose your queen in the same few ways at first. A knight attacks two pieces at once, or you move the pawn that was guarding her. Once someone shows you the patterns, you start to see them coming. React is the same: beginners trip over the same handful of mistakes, and each one is easy to avoid once you know its shape.

The most common React mistakes beginners make are changing state directly, expecting state to change right away, printing a stray 0 with &&, using the index as a key, calling an event handler instead of passing it, using an effect to work out a value, forgetting an effect's cleanup, and defining a component inside another component. Here's what each one looks like, why it happens, and the fix.

Four React mistakes next to their fixes: items.push then setItems becomes setItems with a spread copy, items.length && becomes items.length > 0 &&, key={index} becomes key={tea.id}, and onClick={save()} becomes onClick={save}
Four of the slips below, each fixed in one line.

Changing state directly

Arrays and objects in state are read-only. If you push into an array and hand React the same array, React sees the same array it already had and skips the update. The screen doesn't change.

// Changes the old array, so the screen doesn't update
items.push(tea);
setItems(items);

// Makes a new array, so React sees the change
setItems([...items, tea]);

Add with spread, remove with filter, and change one item with map. Updating arrays in state and updating objects in state show every case. To test yourself, predict what this profile shows after a rename.

Expecting state to change right away

Setting state doesn't change the variable you have. It asks React for a new render, and the new value arrives in that render. So one click on this button adds 1, not 3:

function handleClick() {
  setCount(count + 1);
  setCount(count + 1);
  setCount(count + 1);
}

Inside one render, count is a fixed number. If it's 0, all three calls ask for 0 + 1. When the next value depends on the last one, pass an updater function instead: setCount((c) => c + 1). Each updater gets the value queued before it, so three of them add 3. State as a snapshot explains why, and queueing state updates shows the fix. This counter question asks you to predict exactly what it logs.

Printing a stray 0 with &&

a && b doesn't give back true or false. When a is falsy, it gives back a itself. React shows nothing for false or null, but it shows numbers, so an empty cart prints a 0:

// Shows 0 when the cart is empty
{items.length && <CartList items={items} />}

// Shows nothing when the cart is empty
{items.length > 0 && <CartList items={items} />}

Put a true-or-false test on the left of &&, or use a ternary. See conditional rendering, and try the empty cart question.

Using the index as a key

Keys tell React which item is which from one render to the next. With the index as a key, the key belongs to a position, not to an item. Remove the first row, and the row that was second now has key 0. React keeps the first row's state at key 0, so a note typed for the removed item now sits next to a different one.

{teas.map((tea) => (
  <TeaRow key={tea.id} tea={tea} />
))}

Use an id that comes with the data, or make one when the item is created. The index is only safe for a list that never changes order, only adds or removes items at the end, and holds no state of its own. See rendering lists, and predict what happens when the first row is removed.

Calling an event handler instead of passing it

An event handler is a function you hand to React, for React to call later. Add parentheses and you call it yourself, during rendering:

// Runs save while rendering
<button onClick={save()}>Save</button>

// Runs save on click
<button onClick={save}>Save</button>

// Runs save(tea.id) on click
<button onClick={() => save(tea.id)}>Save</button>

If save sets state, calling it during rendering asks for another render, which calls it again. React stops the loop with a "Too many re-renders" error. Pass the function, or wrap the call in an arrow function. See responding to events.

Using an effect to work out a value

If a value can be worked out from props or state, work it out while rendering. Copying it into state with an effect costs an extra render, and the page shows the old value for one render first.

// Extra state, kept in step by an effect
const [total, setTotal] = useState(0);
useEffect(() => {
  setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);

// Just calculate it
const total = items.reduce((sum, item) => sum + item.price, 0);

Effects are for keeping a component in step with something outside React, like a connection or a timer. You might not need an effect shows what to do instead in each case, and choosing the state structure shows how to keep state small.

Forgetting an effect's cleanup

Every effect that starts something must stop it: a timer, a listener, a subscription, or a connection. Without a cleanup, the old one keeps running after the component leaves or the effect runs again.

useEffect(() => {
  const id = setInterval(() => setSeconds((s) => s + 1), 1000);
  return () => clearInterval(id);
}, []);

In development, Strict Mode sets each effect up, cleans it up, and sets it up again when a component appears. That makes a missing cleanup show at once: a timer with no cleanup counts by 2. Fix the cleanup rather than turning Strict Mode off. See synchronizing with effects and why effects run twice in development.

Defining a component inside another component

React keeps state by a component's type and its place in the tree. A component written inside another one is a brand new function every time the parent renders, so React sees a new type and throws the old one away, with its state and its DOM. Anything it remembered starts over. If typing in it updates the parent's state, its input loses focus after every key press.

Define every component at the top level of its file, and pass it what it needs as props. See preserving and resetting state and the interview question on it.

How do you catch these mistakes early?

  • Keep Strict Mode on in development. Its extra render and extra effect setup make impure components and missing cleanups show straight away. See keeping components pure.
  • Turn on eslint-plugin-react-hooks. It checks the rules of hooks as you type.
  • Read the console. React warns about missing keys, repeated keys, and inputs that switch from uncontrolled to controlled.
  • Practice predicting. Many of the predict-the-output React interview questions are built around these slips. Guess first, then check.

Then fix some for real. The React coding problems include fix-it problems like the order counter and the effect loop, where the bug is one of these mistakes. If you're just starting out, how long does it take to learn React? has a plan, and the React course starts from your first component.

Written by Shrikanth PS

Senior Software Engineer at Microsoft, working on Copilot Enterprise, with more than nine years in frontend engineering.