Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Gloria Tejuosho
Gloria Tejuosho

Posted on

Utilizing the useEffect Hook for Handling Side Effects

TheuseEffect 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 leveraginguseEffect, we can keep our applications organized, efficient, and easy to maintain.

In this article, we'll discuss the best practices for using theuseEffect 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 onFreeCodeCamp.

useEffect Syntax

The useEffect takes two parameters:

  1. A function that handles the side effect logic.

  2. An optional dependency array that determines whether the effect should re-render.

useEffect(()=>{},[])
Enter fullscreen modeExit fullscreen mode

To solidify your knowledge, we will use useEffect to handle a side effect by fetching a list of users data from GitHub.

Step 1: ImportuseEffect anduseState Hook at the top level of your component.

importReact,{useState,useEffect}from"react"
Enter fullscreen modeExit fullscreen mode

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 theuseState.

constUseComponent=()=>{const[users,setUsers]=useState([]);return(<></>)}
Enter fullscreen modeExit fullscreen mode

Step 3: Create aurl variable that holds the link to the API

consturl="https://api.github.com/users";
Enter fullscreen modeExit fullscreen mode

Step 4: Create agetUser function to fetch the data.

constgetUser=async()=>{constresponse=awaitfetch(url);constusers=awaitresponse.json();setUsers(users);}
Enter fullscreen modeExit fullscreen mode

We used theasync 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 theuser's variable.

Step 5: Invoke thegetData function inside theuseEffect.

useEffect(()=>{getUser();)}
Enter fullscreen modeExit fullscreen mode

Step 6: Add the dependency array.

useEffect(()=>{getUser();),[]}
Enter fullscreen modeExit fullscreen mode

The dependency array ensures that the function passed i.egetUsers only runs once after the initial render.
This helps to avoid unnecessary API calls on subsequent renders.

Step 7: Use themap method to display the new data stores in theuser state.

constUseComponent=()=>{const[users,setUsers]=useState([]);return(<><h2>GitHubUsers</h2><ul>{users.map((githubUsers)=>{const{id,login,avatar_url,html_url}=githubUsers;return<likey={id}classname="wrapper"><imgsrc={avatar_url}alt={login}className="image"/><divclassName="text"><h4>{login}</h4><ahref={html_url}/>Profile</a></div></li>})}</ul></>)}
Enter fullscreen modeExit fullscreen mode

Using themap method, we destructured each data in theuser state i.eid,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 theuseEffect 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:

  1. 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.

  2. 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.

  3. 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

  4. Use useEffect for side effects only: Avoiding uses such as handling events, rendering components, or initializing state. ReserveuseEffect 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.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

WEb3/Technical Writer.I write clear, concise, and accurate technical documentation.
  • Location
    Lagos, Nigeria.
  • Education
    Adekunle Ajasin University
  • Pronouns
    She
  • Joined

More fromGloria Tejuosho

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp