admin管理员组

文章数量:1312795

let say I have a functional Home ponent:

const Home = () => {
  console.log('outside useEffect')
  useEffect(() => {
    console.log('inside useEffect')
    
    // cleanup function
    return () => { console.log('unmounted') }
  }, [])

  return <div>Hello Word</div>
}

The output in the console shows:

outside useEffect
inside useEffect
unmounted
inside useEffect

My questions are:

  1. When does the ponent unmount, does it happen automatically after it has rendered once or when?
  2. What exactly does happen when the ponent unmounts? Does the ponent get deleted/removed? If yes then how am I still able to see the Hello World even if it unmounts.

let say I have a functional Home ponent:

const Home = () => {
  console.log('outside useEffect')
  useEffect(() => {
    console.log('inside useEffect')
    
    // cleanup function
    return () => { console.log('unmounted') }
  }, [])

  return <div>Hello Word</div>
}

The output in the console shows:

outside useEffect
inside useEffect
unmounted
inside useEffect

My questions are:

  1. When does the ponent unmount, does it happen automatically after it has rendered once or when?
  2. What exactly does happen when the ponent unmounts? Does the ponent get deleted/removed? If yes then how am I still able to see the Hello World even if it unmounts.
Share Improve this question edited Jul 6, 2022 at 7:53 Youssouf Oumar 46.3k16 gold badges101 silver badges104 bronze badges asked Jul 6, 2022 at 7:02 Aniket Kumar PaulAniket Kumar Paul 1261 gold badge2 silver badges7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Normally a ponent gets unmounted when for example it's rendered conditionally and the conditional bee false. DummyComponent below gets unmounted every time state bee false. And when a ponent is unmounted, it's removed from the DOM, and therefore you won't see it in the page.

const DummyComponent = () => {
  useEffect(() => {
    console.log("mounted");
    return () => {
      console.log("unmounted");
    };
  }, []);
  return <div>Hello Word</div>;
};

const App = () => {
  const [state, setState] = useState(true);
  return (
    <div>
      <button onClick={() => setState(!state)}>Toggle Dummy Component</button>
      {state ? <DummyComponent /> : <></>}
    </div>
  );
};

What you are seeing in your case is introduced by React version 18 where each ponent gets mounted and immediately unmounted and mounted again, when you are in development with StrictMode: it's explained in this thread. And it's so quick that you are not noticing the change visually.

In React 18 Strict Mode, each ponent is unmounted & remounted again.
https://reactjs/blog/2022/03/29/react-v18.html

Perhaps that's why "inside useEffect" is printed after "unmount".

本文标签: