Home > Enterprise >  Why is useEffect cleanup function getting called on first render?
Why is useEffect cleanup function getting called on first render?

Time:05-19

import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
  const [state, setState] = useState(0);
  useEffect(() => {
    return () => {
      // setState(1)
      console.log("inside cleanup");
    };
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {console.log(state)}
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

the console.log() inside of cleanup is getting consoled in browser. i am not sure why is this happening.As per my concepts, cleanup should be called when the component is updating on state change and that state is a part of dependency array, or no dependency array at all

CodePudding user response:

If you are wrapping you app in <StrictMode> your components will be mounted / unmounted / remounted to identify potential unsafe lifecycles. This only occurs on developement mode.

CodePudding user response:

useEffect cleanup function does not only run when our component wants to unmount, it also runs right before the execution of the next scheduled effect.

In fact, after useEffect executes, the next scheduled effect is usually based on the dependency(array).

In strict mode, development build, useEffect is executed twice. So a cleanup is run post the next scheduled effect. From react docs

effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.

CodePudding user response:

import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
  const [state, setState] = useState(0);

All the code here is getting called only once

useEffect(() => {
    return () => {
      // setState(1)
      console.log("inside cleanup");
    };
  }, []);

All the code here is getting called on every state update, on first render or when its parent is updated

return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {console.log(state)}
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );

}

  • Related