I read this article React Hook to Run Code After Render and came across this line React can and will sometimes call your components multiple times before actually rendering them to the screen, so you can’t rely on “one call == one render”.
Can someone please explain what he meant ?
I wrote this code
function x() {
console.log("x");
}
function y() {
console.log("y");
return "y";
}
function Silicon() {
console.log("silicon");
return <div></div>;
}
function useDarko() {
const [count1, setCount1] = useState(0);
console.log("useDarko");
return [count1, setCount1];
}
export default function Test0022() {
const [darko, setDarko] = useDarko();
const [count1, setCount1] = useState(0);
x();
useEffect(() => {
if (count1 !== 200)
setTimeout(() => {
setCount1((e) => ++e);
}, 100);
}, [count1]);
return (
<>
<Silicon />
{y()}
</>
);
}
I always see 804 console.log, it works as expected one call == one render.
For about 4 years, react has been working to implement a feature called "concurrent mode" (yes, it had been announced long before that article was released). It will be in version 18 of react, which is currently in a release-candidate state.
Concurrent mode allows react to abort a long-running render part way through in order to handle a more important update. This new approach has implications for lifecycle hooks and for the behavior of side effects, and as a result the react team has been training the community to start writing their code in a way that works with concurrent mode. For example, they deprecated several class component lifecycle hooks that would not be safe with the new approach.
And as the article mentions, one of the mental models we need to get used to is that a component may be called multiple times before it actually makes it on to the screen. Your component may get called, run all the way through, and then react realizes it needs to throw out that work and start over. These cases are rare, but to help you catch problems you can use strict mode. Among other things, it will deliberately double-render your components in development builds, to make it easier to spot bugs that only occur when these double-rendering cases occur.
Note that in react 17 this strict-mode double-render overwrites the console.log function so that it has no effect, and as a result it's difficult to see that it's happening.