In class components you have access to "lifecycle methods" which can be used to as a means to execute code at specific points in a component's lifecycle (such as on initial render with componentDidMount
, on re-render with componentDidUpdate
, and on removal from the DOM with componentWillUnmount
).
While these class component lifecycle methods offer a more explicit syntax which can make it easier for developers to directly identify the parts of the code that do what (and at various points), it can lead to duplication in the code. For example, you might see componentDidMount
for a “counter click” task and a componentDidUpdate
for another click.
The useEffect
hook allows you to add side effects to function components, mimicking much of the functionality of lifecycle methods in class components. It helps reduce the code duplication by basically combining componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle methods into one efficient function.
To use the useEffect
hook, we first need to import it:
import React, { useEffect } from 'react';
There are then two main parts of the hook:
- the "effect", which is the function declared as the first argument of the hook, and
- the "dependency array," declared as the second.
useEffect(() => {
// effect
}, [data]); // optional dependency array
The first argument is always going to be some kind of function to be executed. The second argument determines when that function is executed.
There are three possible ways to configure our useEffect
's dependency array. Below is a list of dependency array configurations and the implication on when the hook is executed.
[]
- we can use an empty array. This will cause the hook to behave similar to acomponentDidMount
and run at initial render only. When the component first renders on the DOM, theuseEffect
will be called.[data]
- we can include some data (one or more elements). With an array with data in it, our effect will run at the initial render, and will also run after every re-render if the data has changed since the last render – a kind-of combo ofcomponentDidMount
andcomponentDidUpdate
....
(nothing) - if we exclude the dependency array entirely, our effect is called when the component is rendered for the first time AND whenever it re-renders.
The dependency array affords us a ton of flexibility in how our code is executed and when. I'll leave you with a useful codesnap to reference when implementing the useEffect
hook.