Chris Manciero
Quick Example of React useEffect Hook
In my previous post (Accessing State with React Hooks), I discussed how easy it is to add state to your React function component. This post will discuss how the useEffect Hook allows you to use the class life cycle methods (example: componentDidMount, componentDidUpdate and componentWillUnmount) in your function component.
The useEffect Hook allows you to perform actions after render of your component. Example actions are fetching data from an API, subscribing to a service, or updating DOM elements.
In my auto-complete search box component (code below) I use a useEffect hook to add and remove event listeners to my document.
// collection of event listeners to add
function addListeners() {
document.addEventListener("keydown", onKeyPressHandler, false);
document.addEventListener("click", onOutsideClick, false);
}
// collection of event listeners to remove
function removeListeners() {
document.removeEventListener("keydown", onKeyPressHandler, false);
document.removeEventListener("click", onOutsideClick, false);
}
useEffect(() => {
addListeners();
return () => {
removeListeners();
};
});
Here is a break down of the code to give an understanding as to what is happening in the useEffect hook.
We can ignore the addListeners and removeListeners methods because those are just basic addEventListener and removeEventListeners calls to the document object. I just created these method to keep the code better organized. Here is the main code we want to examine:
useEffect(() => {
addListeners();
return () => {
removeListeners();
};
});
The first part of my code is making a call to the useEffect hook and passing in a function as a parameter. This function will call the addEventListeners method after React has finished updating the DOM. This is similar to making method calls in componentDidUpdate and componentDidMount.
The second part, the return function call, is where any clean up actions should be called. This is similar to making a method call in the componentWillUnmount method.
If I did not need to clean up my event listeners I would write my useEffect hook like this:
useEffect(() => {
addListeners();
});
Only run useEffect on data changes
There may be times when you only want the useEffect method call to be executed when a value has changed for a property. If that is the case you pass an array of properties to check as another argument to the useEffect method.
useEffect(() => {
addListeners();
}, [searchTerm]);
Now the useEffect method will be fired only when the value stored in searchTerm has changed on render.
Code example
Here is a sample application I made that uses the useEffect hook.