What is the useEffect hook?
The useEffect hook handles side effects in React. A side effect happens when you interact with something outside the scope of React.
Some common examples of side effects are;
- Data fetching.
- Interacting with local storage.
- Using timers.
The useEffect hook replaces the following lifecycle methods in class-based React.
componentDidMount
.componentDidUpdate
.componentWillUnmount
.
Syntax for useEffect
To use useEffect, you first import the hook from React. Then, you can use it within your functional component.
import React, { useEffect } from 'react';
The syntax is as follows.
useEffect(<Callback Function>, <Dependency Array>)
The useEffect hook takes two arguments.
A callback function. useEffect runs the function at least once when the component is rendered. Then, based on the dependency array, it may run again with later renders (more on that later).
A dependency array. This argument (an array) is optional. But it is generally recommended that you include a dependency array in useEffect. Whether useEffect runs again depends on what is in the array.
There are three ways to determine when useEffect should run. You can choose which one to use with the dependency array.
1. Run useEffect after every render
When you don't provide a dependency array, useEffect will run after every render of your component.
function ExampleComponent() {
useEffect(() => {
console.log("No dependency array. Runs after every render")
})
return (
// ...some JSX
)
}
In the example above, useEffect will run whenever the ExampleComponent renders. That is because there is no dependency array.
2. Run useEffect only on the first render
Sometimes, you may want to run useEffect only after the first render.
For example, when you're fetching data to update some state variable. To do that, you need to include an empty array.
function ExampleComponent() {
useEffect(() => {
console.log("Runs only after the first render.")
}, [] )
return (
// ...some JSX
)
}
The difference here is the inclusion of the empty array. With an empty dependency array, React knows to run useEffect only once.
3. Run useEffect after changes in dependent variables.
What happens when you provide an array with variables instead?
First, useEffect will run after the initial render. Then, React keeps an eye on the values in the array. If any of the values changes, useEffect will run again.
function ExampleComponent() {
useEffect(() => {
console.log("Runs after a change in any of the values.")
}, [firstValue, secondValue, thirdValue] )
return (
// ...some JSX
)
}
In this example, the second argument of useEffect is an array with three values. React will run useEffect anytime there's a change in firstValue, secondValue, or thirdValue.
The cleanup function in useEffect
Sometimes, you will face situations where the side effect lingers after the component unmounts.
Destroy (or clean up) side effects when the component is unmounted from the DOM.
To use a cleanup function, add a return function from useEffect like so.
useEffect(() => {
// perform effect here...
return () => {
// perform cleanup here...
};
}, [])
The cleanup function helps avoid memory leaks and unexpected behaviors. Examples of cases where you will need a cleanup function include the following;
- Removing event listeners.
- Stopping intervals and timers.
- Cleaning up subscriptions.
Here is an example of using a cleanup function.
import React, { useState, useEffect } from 'react'
function MyComponent() {
const [online, setOnline] = useState(false)
useEffect(() => {
let timer = setTimeout(() => setOnline(true), 5000)
return () => {
clearTimeout(timer)
}
}, [])
}
In this example, the online status is set to false when a user opens the app. We use the timer to wait for 5 seconds before setting the online status to true.
In this case, we use the cleanup function to avoid creating a timeout in memory.
Conclusion
And that's all for this tutorial on useEffect. Congratulations on making it this far! You should now be familiar with the following;
- What is the useEffect hook?
- How to use useEffect in react.
- The dependency array and how to use it.
- The cleanup function.
If you have any questions, you can ask in the comment section below. Or check out the next react hook tutorial on useRef.