P粉8212742602023-08-14 10:16:44
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:
export default function App() { useEffect(() => { console.log("first"); return () => console.log("Unmount App"); }, []); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> </div> ); }
Now the order of the logs will look like this:
first Unmount App first
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.