React Foundations ยท State

Updating objects and arrays

Immutable state updates

Updating objects and arrays

You add an item to a list in state, and nothing happens on screen. The list is right there in memory, but React did not re-render.

React compares the old state and the new state by reference. Change an array in place with push and the reference is the same, so React sees no change and skips the render.

State is replaced, not mutated. When state holds an object or an array, build a new one and pass it to the setter:

setItems((current) => [...current, 'c']);

The spread (...) copies the existing items into a new array, and 'c' is appended. The new array is a different reference, so React re-renders.

The same idea applies to objects:

setUser((current) => ({ ...current, name: 'Ada' }));

Always create a new object or array; never change the one already in state. The component you are editing is exported from App.jsx.

Your job is to append an item to a list held in state.

Challenge

The list is fixed at two items and the button that adds another does nothing. Export an App component from App.jsx that keeps a list of items in state, starting with a and b, and renders a button labelled Add that appends c to the list.

The Test clicks the button once and expects three list items. The starter renders a fixed list and never updates it, so the Test fails.

App.jsx
export function App() {
  return (
    <div>
      <ul>
        <li>a</li>
        <li>b</li>
      </ul>
      <button>Add</button>
    </div>
  );
}

No test run yet

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