Replacing Component Lifecycle Methods with the useEffect Hook

Jamund Ferguson
InstructorJamund Ferguson

Share this video with your friends

Send Tweet

The useEffect hook provides a way for components to declaratively state side effects that need to be run. By modifying the dependency array you can simulate certain React lifecycle methods such as constructor/componentDidMount and componentDidUpdate and componentWillUnmount. The useEffect hook is always called after the first render of your component and then any time its dependencies change.

Examples

componentDidMount() {
    fetchData();
}

Is functionally equivalent to:

useEffect(() => {
   fetchData();
}, [])

Likewise this common approach:

componentDidUpdate(prevProps) {
   if (this.props.someProp !== prevProps.someProp) {
     handleChange();
   }
}

Can be replaced with the following hook:

useEffect(() => {
  handleChange();
}, [someProp);

There is also a cleanup phase that happens with hooks. If you return a function inside of a hook it will be executed just before the function is unmounted. This is similar to the componentWillUnmount hook and is explained in detail here: https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup