Utilizing the useEffect Hook for Handling Side Effects
Gloria Tejuosho
Posted on June 30, 2024
The useEffect
hook is a crucial tool in React for managing side effects, i.e., actions that occur outside the scope of a component.
Examples of side effects include:
- Fetching data
- Event listeners
- Setting and clearing timers
- Updating the DOM
By leveraging useEffect
, we can keep our applications organized, efficient, and easy to maintain.
In this article, we'll discuss the best practices for using the useEffect
hook in our projects.
Before we proceed, you need to have a basic understanding of React fundamentals, including:
- React components
- Basics of react hooks
If you need a refresher, check out this article on FreeCodeCamp.
useEffect Syntax
The useEffect takes two parameters:
A function that handles the side effect logic.
An optional dependency array that determines whether the effect should re-render.
useEffect (()=>{
},[])
To solidify your knowledge, we will use useEffect to handle a side effect by fetching a list of users data from GitHub.
Step 1: Import useEffect
and useState
Hook at the top level of your component.
import React, {useState, useEffect} from "react"
useState
will create a state variable that stores the users’ data.
useEffect
will handle the side effects when fetching the data.
Step 2: Create a component and declare the useState
.
const UseComponent = ()=>{
const [users, setUsers] = useState ([]);
return (
<>
</>
)
}
Step 3: Create a url
variable that holds the link to the API
const url = "https://api.github.com/users";
Step 4: Create a getUser
function to fetch the data.
const getUser = async()=>{
const response= await fetch(url);
const users = await response.json();
setUsers (users);
}
We used the async await
method to fetch the data.
response: This fetches the data from the url variable.
users: Gets the response variable and changes it to a json.
setUsers: This function updates the user's state from an empty array to hold the fetched data in the user
's variable.
Step 5: Invoke the getData
function inside the useEffect
.
useEffect (()=>{
getUser();
)}
Step 6: Add the dependency array.
useEffect (()=>{
getUser();
),[]}
The dependency array ensures that the function passed i.e getUsers
only runs once after the initial render.
This helps to avoid unnecessary API calls on subsequent renders.
Step 7: Use the map
method to display the new data stores in theuser
state.
const UseComponent = ()=>{
const [users, setUsers] = useState ([]);
return (
<>
<h2> GitHub Users</h2>
<ul>
{
users.map((githubUsers)=>{
const {id, login, avatar_url, html_url} = githubUsers;
return <li key={id} class name="wrapper">
<img src={avatar_url} alt={login} className="image"/>
<div className="text">
<h4> {login} </h4>
<a href={html_url}/>
Profile
</a>
</div>
</li>
})
}
</ul>
</>
)
}
Using the map
method, we destructured each data in the user
state i.e id
, login
, avatar_url
, html_url
properties
and they are assigned to each html tag.
This makes the user data fetched from the API display.
Notice how we used the useEffect
hook to handle the side effect of fetching data from an API, and implemented a dependency array to ensure that the API call only executes after the initial render.
This optimises the performance and also prevents redundant data fetching.
Best practices when using useEffect
UseEffect is a crucial tool in React applications, and best practices should be followed when using it to avoid slowing down the application's performance and unnecessary re-renders.
These include:
Always use the dependency array as the second argument in useEffect.
The dependency array ensures that the effects only execute when the specified dependencies change, preventing unnecessary re-renders.Use the clean-up function: The cleanup function helps remove unnecessary side effects, preventing memory leaks.
E.g. Using the cleanup function to clean up a timer like setTimeout or setInterval prevents them from running unnecessarily and avoids memory leaks.Use multiple useEffect for unrelated logics: When dealing with multiple unrelated logics, it's essential to use separate useEffect hooks for each logic, making your code more readable, manageable, and easier to understand. E.g
Use useEffect for side effects only: Avoiding uses such as handling events, rendering components, or initializing state. Reserve
useEffect
for tasks like fetching data, setting timers, or updating the DOM, which has a tangible impact on the component's behaviour.
Conclusion
In this article, we examined the useEffect hook, its purpose, and when to use it.
Additionally, we discussed best practices for using the useEffect hook to ensure optimised code in our React application.
Posted on June 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.