Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 534
Mahdi Faraji Avatar asked Oct 12 '25 10:10

Mahdi Faraji


1 Answers

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");
  }
}
like image 198
Alan Omar Avatar answered Oct 13 '25 22:10

Alan Omar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!