The useEffect
hook, which listens for changes, is a hook that executes a block of code when something changes or a function is triggered. Essentially, the useEffect
hook lets you perform side effects in functional components when the application mounts or when the state or prop gets updated. Some of the operations performed with the useEffect
hook include:
- Fetching requests from an external API.
- Manipulating the Document Object Model (DOM).
- Using a timer function like
setTimeout()
that runs for a certain period.
This article shows you how the useEffect
hook in React works. React is one of the most common JavaScript libraries for building user interfaces (UIs).
Rules when using hooks
- Hooks must only be used in the function components.
- Hook must only be used at the component top-level (not in it).
- There can be no
return
before any hook.
The above rules should not be regarded as the use case for only
useEffect
, but for any hook you decide to use, even custom hooks.
Let's try to use the hook.
useEffect(() => {
// put your code here
}, dependencies)
The syntax above for the useEffect
hook takes a callback function, and an argument called dependencies
. dependencies
, denoted with an array-like symbol []
, is optional.
For the use case above, the useEffect()
hook executes the callback only once.
useEffect(() => {
console.log('Public technical writing competition')
})
Here, the useEffect
hook has no dependency, and it emits the message "Public technical writing competition" every time the page renders.
To resolve it, we follow the first example of adding a dependencies
array.
With variables
useEffect(() => {
doSomethingWith(value);
}, [value])
With the snippet of code above, useEffect
triggers side effects each time a prop or state is updated. The array will consist of all of the state variables and props that watched for updates comparable with the componentDidUpdate
life cycle method.
Fetching Data
Now its time to write a practical use case with the useEffect
hook in fetching data from a RESTful API.
import { useEffect, useState } from 'react'
// other imports go below here
const [posts, setPosts] = useState([]);
useEffect(() => {
fetchPosts();
}, [])
const fetchPosts = async () => {
const url = 'https://jsonplaceholder.typicode.com/posts/'
const res = await fetch(url)
const data = await res.json();
setPosts(data);
}
const fetchData = () => {
return (
<div>
{/* Rendered JSX goes in here */}
</div>
)
}
export default FetchData;
In the code above, we created a fetch data component and used a fake API.
To get this working, we used the useEffect
hook and called the fetchPosts
in the callback function, which is an asynchronous function to retrieve data. Once the data is retrieved, we update the posts with the setPosts
function, which accepts a new state value and enqueues a re-render of the component.
The
useState
hook we imported is another hook used to return a state and a function to update that state. To learn more, read this.
Comments (0)