Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks call setState with same primitive value still cause re-render

I find that when I define a state with the value '1',

and set the state with the value '2' every time when I click a button,

the first two times will cause re-render

reproduce demo: https://codesandbox.io/s/sweet-brattain-ys11d

code: using react@17 without strict mode

import { useState } from "react";

export default function App() {
  const [a, setA] = useState("1");
  console.log("render", a);
  return (
    <button
      onClick={() => {
        setA("2");
      }}
    >
      {a}
    </button>
  );
}

// log:
// render 1
// render 2
// render 2

I can understand the first re-render because the state changed to '2' from '1',

but I don't understand the second re-render

like image 651
Littlee Avatar asked Oct 19 '25 11:10

Littlee


1 Answers

I think this explains the anomaly very well:

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo

Note the last paragraph. This is quoted directly from here.

like image 50
codemonkey Avatar answered Oct 22 '25 01:10

codemonkey