Search code examples
javascriptreactjsreact-hooksreact-lifecyclereact-lifecycle-hooks

React functional component useEffect hook with dependency equal in class component lifecycles


I use the useEffect hook inside functional components with a dependency so that dependency changes , useEffect function will re-run like this :

const [show, setShow] = React.useState(false);

React.useEffect(() => {
 
    console.log("Do something")

} , [show]);

I wanted to know what is available in react's class component to do exactly like this ? Is there any lifecycle method to have this functionality ?


Solution

  • you can use combination of componentDidMount and componentDidUpdate:

    componentDidMount(){ //use this method if you want to trigger the side effect first time
       console.log("Do something")
    }
    
    componentDidUpdate(prevProps,prevState) {
      if (this.state.show !== prevState.show) {
        console.log("Do something");
      }
    }