Replacing Component Lifecycle Methods with the useEffect Hook

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

V Chan
V Chan
~ 2 years ago

The redux-linting has a warning: React Hook useEffect has a missing dependency: 'getLatestExchangeRates'. Either include it or remove the dependency array. eslint(react-hooks/exhaustive-deps) I would be curious why currencyCode is not sufficient to satisfy the minimum.

Lucas Minter
Lucas Minter
~ 2 years ago

Hey V, here is a link to stack overflow explaining the reason for needing to pass the function into the useEffect dependency array. https://stackoverflow.com/questions/62601538/passing-a-function-in-the-useeffect-dependency-array-causes-infinite-loop