react hook 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

10 thoughts on “react hook call setState with same primitive value still cause re-render”

Leave a Comment