5

This is my code

import { useEffect } from "react";
import { Link } from "react-router-dom";

export const PageOne = () => {

    useEffect(() => {
      return () => {console.log("PageOne")}
    }, []);

    return (
        <>
            <h1>PageOne</h1>
            <Link to="/two">Page two</Link>
        </>
    );
}

This is what I see in the console when visit PageOne

PageOne

This is what gets printed in the console when I navigate from PageOne to PageTwo (PageOne and PageTwo have the same structure)

PageOne
PageTwo 

So I think that the return function defined in useEffect runs when the component is mounted and unmounted. I am using react-router-dom and Vite in this project.

Is this normal? And, does there exist a way to run a side-effect function only when a component will be unmounted?

Sorry if I made some mistakes. I am a new developer and an English student.

  • 2
    Could be React strict mode, which mounts components twice to achieve better error checking. https://reactjs.org/docs/strict-mode.html – don_aman Jul 14 '22 at 22:31
  • 1
    yep, you can see some arguments for this behavior in this issue here https://github.com/facebook/react/issues/24502#issuecomment-1121089680 – Cristian-Florin Calina Jul 14 '22 at 22:39

2 Answers2

3

it happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.

if you see docs

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions ...

Hasan Haghniya
  • 2,347
  • 4
  • 19
  • 29
1

I think your question has been misunderstood but the explanations about StrictMode provided by the other users are correct.

Now, to answer what I think is your actual question: useEffect's clean up function not only executes when your component is about to unmount, it also runs to clean up previous renders' effects before actually running the next scheduled effect.

Conclusion: Don't worry, this is a expected behaviour. I will leave the link to React's docs where this is explained.

ivanatias
  • 3,105
  • 2
  • 14
  • 25