0

here's an example component that shows this behavior:

const App = () => {
  const [testArray] = useState([{key: "hi", value: "Hello "}, {key: "world", value: "world"}]);
  const [otherState, setOtherState] = useState("Change");

  function renderTestArray() {
    return testArray.map(entry => <span key={entry.key}>{entry.value}</span>);
  }

  function updateTestArray() {
    testArray[0].value = testArray[0].value === "Goodbye " ? "Hello " : "Goodbye ";
    setOtherState((prevState) => prevState === "Change" ? "Test" : "Change");
  }

  return (
    <Fragment>
      <div>
        {renderTestArray()}
      </div>
      <button onClick={updateTestArray}>{otherState}</button>
    </Fragment>
  );
};

When I press the Change button, I would expect the button label to change but not the "Hello World" message since the setState for that array is not being called. What I don't understand is how React is picking up that the testArray changed and then rendering that change. Also how is it that the testArray change is being persisted in subsequent renders even if its setState is not being called.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • 2
    `testArray[0].value = /**/` this [mutates the current state](https://stackoverflow.com/q/37755997/1218980) and it's an anti-pattern in React. – Emile Bergeron Apr 22 '21 at 15:08
  • 1
    You are mutating that object (and the useState will bring back the same object). The thing is that since you call the `setOtherState` it will cause a re-render and so you will see the mutation in the `testArray`. Otherwise, if you just mutated the object, it would not cause a re-render. – Gabriele Petrioli Apr 22 '21 at 15:10
  • So basically every time that I call a `setState`, React checks all state variables for re-renders even if the called `setState` was for an specific state variable? – David Vargas Apr 22 '21 at 15:15
  • Manually mutating the current state (without setState) won't trigger a render on its own, but since you're also calling setState somewhere else, React just re-render with the current state, which you have mutated manually before. – Emile Bergeron Apr 22 '21 at 15:30
  • It re-renders the whole component where some state changed. – Ben West Apr 22 '21 at 18:49

0 Answers0