react router unmount function component
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
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.
}
}, [])
}
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');
};
}, []);