Search code examples
reactjsreact-hookscomponentsuse-effect

React UseEffect with empty array dont trigger return function


I'm trying to use a return function inside the body of useEffectF, to implement certain logic.

But if I have an empty array of dependencies, the returned function is not called

  useEffect(() => {
    // works good
    console.log('useEffect');
    console.log('useEffect', currentFilter , referenceStore.Filters?.CurrentFilter?.FilterId);
    return () => {
        // does not work
        console.log('return function has been called') 
    }
}, []);

Any ideas why this behavior is possible? because in the examples and in the documentation everything works ok

thanks advance!


Solution

  • Core answer: returning a function from a useEffect means that this function will be called when the component unmounts. Not on first render, as your question seems to suggests.

    If you want to see it called, you can wrap your root component in the StrictMode component (will only work if the React version is >= 18). See: https://codesandbox.io/s/falling-worker-duzty0?file=/src/App.js

    https://reactjs.org/docs/strict-mode.html

    The reason why it does not fire without strict mode and/or React version < 18 is because of this

    With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component:

    Mount -> log "useEffect"

    Unmount -> cleanup fn is called, log "return function has been called"

    Mount -> log "useEffect"

    As the comment by Brian Thompson underlined, this is only active in development mode, not in a production build.