react router unmount function component

13,879

Solution 1

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works. ...read more

Now your effect is called on every rerender of Cmp component. You have to pass the second argument with an empty array to useEffect if you want to call your effect only on unmounting:

useEffect(() => {
    return () => {
        console.log('******************* UNMOUNTED');
    };
}, []);

Solution 2

This is a very common issue people are facing with useEffect hook.

useEffect hook will be called everytime the component is re-rendered. The second argument of hook expects a dependency array, so the hook will only be called if the dependencies have changed. And if you provide empty array to it, hook will run only on mount and the returned function will be called before unmount.

TIP: Add this ESLint plugin to your project to find such hooks related issues. https://www.npmjs.com/package/eslint-plugin-react-hooks

import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom';

import './styles.css';

const DemoComponent = () => {
  useEffect(() => {
    return () => {
      console.log('******************* UNMOUNTED');
    };
  }, []);
  return <div>Demo Component</div>;
};

const HomeComponent = () => {
  return <div>Home Component</div>;
};

function App() {
  return (
    <BrowserRouter>
      <div>
        <Link to="/">To Home</Link>
        <br />
        <Link to="/aaa">To AAA</Link>
        <br />
        <Link to="/bbb">To BBB</Link>
      </div>
      <Switch>
        <Route path="/(aaa|bbb)" component={DemoComponent} />
        <Route path="/" component={HomeComponent} />
      </Switch>
    </BrowserRouter>
  );
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);  

Here is the working example: https://codesandbox.io/s/9l393o7mlr

Solution 3

Combining both componentDidMount and componentWillUnmount

This means that you can use componentDidMount and componentWillUnmount in the same useEffect function call. Dramatically reducing the amount of code needed to manage both life-cycle events. This means you can easily use componentDidMount and componentWillUnmount within functional components. Like so: More Updates please React: UseEffect

import React, { useEffect } from 'react';
    const ComponentExample => () => {
        useEffect(() => {
            // Anything in here is fired on component mount.
            return () => {
                // Anything in here is fired on component unmount.
            }
        }, [])
    }
Share:
13,879

Related videos on Youtube

Naor
Author by

Naor

My name is Naor and I live in the holy city Jerusalem of Israel. I am 31 years old, married to my lovely Ilana and we have a female cat named Mutzi. I am working as web developer and I create web apps in my free time.

Updated on September 15, 2022

Comments

  • Naor
    Naor over 1 year

    I am using React Router and have two routes that render the same component:

    <Switch>
        <Route path="/aaa" component={Cmp} />
        <Route path="/bbb" component={Cmp} />
    </Switch>
    

    This is Cmp implementation:

    class Cmp extends Component {
        componentWillUnmount() {
            console.log('******************* UNMOUNTED');
        }
    
        render() {
            return null;
        }
    }
    

    As I expect, navigating between /aaa and /bbb doesn't unmount Cmp.

    I am moving to hooks so I rewrote the component:

    function Cmp() {
        useEffect(() => {
            return () => {
                console.log('******************* UNMOUNTED');
            };
        });
    
        return null;
    }
    

    And very surprisingly, when running the app, navigating between /aaa and /bbb console.log that Cmp was unmounted.
    Any idea how to prevent the unnecessary unmount-mount using function component and hooks?