score:19

Accepted answer

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');
    };
}, []);

score: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.
            }
        }, [])
    }

score:5

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


Related Query

More Query from same tag