Why re-render without changing props or state?
P粉786800174
2023-08-13 11:04:44
<p>We have a very simple application that just contains a <code>useEffect</code>, which contains a <code>console.log("first")</code>.
The problem is, I want <code>console.log("first")</code> to only print once when executed, but I don't know why the re-rendering happens, and it prints twice. Please guide me, thank you. </p>
<pre class="brush:php;toolbar:false;">export default function App() {
useEffect(() => {
console.log("first");
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}</pre>
<p>https://codesandbox.io/s/silly-kilby-yn38cj?file=/src/App.tsx</p>
This is a new feature in Strict Mode in React 18, this behavior is intentional. The main reason for this new feature is to remind developers to add cleanup functions in effect processing functions. So basically the component will be mounted twice, meaning it is mounted, unmounted and remounted. However, it's important to know that this behavior is only observed in development mode and does not occur in production builds. To verify the behavior in development mode, add a cleanup function to your effect handler and try logging something. For example:
Now the order of the logs will look like this:
This way developers can ensure that components are not error-prone and perform proper cleanup when components are uninstalled. To understand this better, you can refer to the this example demonstrated in the documentation. If you want to know more about the cleanup work in the effect handler function, please refer to this article.