When using useState in a component, this component will rerender twice, whereas nor the state nor the props did change.
React version: 16.13.1
Link to code example: codesandbox
import React from "react";
let count = 0;
const App = () => {
const [a] = React.useState("render");
count++;
console.log(a, count);
return <div>{count}</div>;
};
export default App;
Logs are:
render 1
render 2
render 1
Same problem. When removing React.StrictMode it solves the problem
Same problem. When removing React.StrictMode it solves the problem
When removing useState and useEffect it solves the problem,too.
Same problem. When removing React.StrictMode it solves the problem
When removing useState and useEffect it solves the problem,too.
Removing the component solves the problem too xD
Same problem. When removing React.StrictMode it solves the problem
When removing useState and useEffect it solves the problem,too.
Removing the component solves the problem too xD
haha~, you make me laugh...
It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.
Source: https://github.com/facebook/react/issues/15074#issuecomment-471197572
Ok, my bad then. I didn't know at all about this feature. Should strict mode log a message in develpment to warn about this or anything? I think it is hard for devs to discover about the source of what they may experience in the current state of things.
@Sharcoux I think Sebastian already worked on this part: PR.
But as a general rule, React doesn't promise anything about when and how many times it calls our function. So it might call the render function multiple times even outside of the StrictMode.
Cool, thanks for sharing. I learned something new.
Side effects in render-phase lifecycle methods will break when enabling Concurrent mode.
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
I can confirm this is fixed in https://github.com/facebook/react/pull/18547 and the fix will be included in React 17. To be clear, the component will still run twice, but the console.log
will be disabled on the second run.
Most helpful comment
Removing the component solves the problem too xD