Home  >  Q&A  >  body text

Why re-render without changing props or state?

<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>
P粉786800174P粉786800174456 days ago554

reply all(1)I'll reply

  • P粉821274260

    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.

    reply
    0
  • Cancelreply