简体   繁体   中英

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

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 .

I think something missing in the code. I checked on my end. it's working fine as per our expectations.

Thanks

import React from "react";
import "./styles.css";
import { useState } from "react";

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM