React Foundations · Robustness & DX

Why your component renders twice

Strict Mode

Why your component renders twice

The first time you wrap your app in <StrictMode>, React renders every component twice. A console.log in your render prints twice. Nothing is broken — React is checking that your render is pure.

A pure render returns the same JSX for the same props and state, and changes nothing outside itself. This component is pure: run it twice and you get the same list.

function Cart() {
  return (
    <ul>
      {items.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

Now imagine the render pushed a new item onto items. The second render would see the longer array, so a double render would produce a different result than a single one. Strict Mode shows you that bug now; production would show it the first time React re-rendered for an unrelated reason.

The rule behind all of this: render computes, it does not change. Put side effects — DOM work, subscriptions, logging — in an effect or an event handler, never in render. (Strict Mode re-runs your effects in development for the same reason: an effect must be able to clean up after itself.)

Your job is to keep a component's render pure under Strict Mode.

Challenge

A cart doubles its items in development, because it mutates the list while it renders. Export an App component from App.jsx that renders a Cart list inside <StrictMode>. Cart renders each item of the module-level items array as an <li> in a <ul>, and it must not mutate items while it renders.

The Test renders your component and expects exactly one list item, even though Strict Mode renders Cart twice. The starter pushes into items during render, so the second render duplicates the item and the Test fails.

App.jsx
import { StrictMode } from 'react';
const items = [];
function Cart() {
  items.push('apple');
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}
export function App() {
  return (
    <StrictMode>
      <Cart />
    </StrictMode>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.