Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing componentDidUpdate with useEffect

Tags:

reactjs

I'm replacing lifecycle methods in class based component into useEffecthooks since I'm into functional component. I'm not sure I'm using useEffect properly..

we can't point previous state or props in useEffect, how can I deal with these with useEffect?

Let's say we have props named src, and I want to check if this src has changed, If not, there would be some logic for it.

componentDidUpdate(prevProps) {
  const { src } = this.props; 

if(prevProps.src !== src) {
   this.cleanUp(); 
   this.init(); 
} else{
   // todo something 
}
}

how can I deal with this using useEffect?

like image 377
dante Avatar asked Oct 14 '25 04:10

dante


1 Answers

Think of useEffect has a "hook" in this case, that relies on something to trigger it when there's a change.

If you give useEffect nothing, it will just be triggered once on load. This is the equivalent to componentDidMount.

If you give it multiple object or elements to follow it will trigger based on the changes of those elements.

TL;DR:

const App = props => {
   useEffect(() => {
      // your code
   }, [props.yourPropertyToWatch]);
}

UPDATE

Based on @hmr's feedback, it would be ideal to add the clean up as well, which is the equivalent of componentWillUnmount.

const App = props => {
   useEffect(() => {
      // your code

      // once done with the component
      return () => {
         // your unmount code
      }
   }, [props.yourPropertyToWatch]);
}
like image 148
codingwithmanny Avatar answered Oct 16 '25 22:10

codingwithmanny



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!