Skip to content
Advertisement

Why is useState not triggering re-render?

I’ve initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:

function App() {
  const [numbers, setNumbers] = React.useState([0, 1, 2, 3]);
  console.log("rendering...");
  return (
    <div className="App">
      {numbers.map(number => (
        <p>{number}</p>
      ))}
      <input
        type="text"
        value={numbers[0].toString()}
        onChange={newText => {
          let old = numbers;
          old[0] = 1;
          setNumbers(old);
        }}
      />
    </div>
  );
}

Based on this code, it seems that the input should contain the number 0 to start, and any time it is changed, the state should change too. After entering “02” in the input, the App component does not re-render. However, if I add a setTimeout in the onChange function which executes after 5 seconds, it shows that numbers has indeed been updated.

Any thoughts on why the component doesn’t update?

Here is a CodeSandbox with the proof of concept.

Advertisement

Answer

You’re calling setNumbers and passing it the array it already has. You’ve changed one of its values but it’s still the same array, and I suspect React doesn’t see any reason to re-render because state hasn’t changed; the new array is the old array.

One easy way to avoid this is by spreading the array into a new array:

setNumbers([...old])
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement