Skip to content
react

Complete Guide to useEffect Hook in React

May 29, 2021Abhishek EH9 Min Read
Complete Guide to useEffect Hook in React

What is useEffect?

useEffect is a react hook that lets you run side effects inside a functional component. Side effects can be any operation that does not interfere with the main execution of the component, like:

  • Directly manipulating the DOM.
  • Fetching data from an API in the background.
  • Running a function after a certain amount of time using setTimeout or at each interval using setInterval.

The syntax

useEffect has the following syntax:

1useEffect(
2 () => {
3 // the callback function which has the side effect you want to run
4 return () => {
5 /* this is an optional cleanup callback,
6 which will be called before the next render */
7 }
8 },
9 [
10 /* this an optional array of dependencies.
11 The useEffect callback runs only when these dependencies change*/
12 ]
13)

It might look overwhelming at first sight. Do not worry! In this tutorial, we will break it into pieces and learn all the practical combinations and applications of useEffect.

The simplest useEffect

Since the only mandatory parameter of an useEffect is the callback function, let's write one with just the callback:

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [count, setCount] = useState(0)
5
6 useEffect(() => {
7 console.log("Running useEffect")
8 document.title = `You clicked ${count} times`
9 })
10
11 console.log("Running render")
12 return (
13 <div className="App">
14 <button onClick={() => setCount(count + 1)}>Click Me</button>
15 </div>
16 )
17}
18
19export default App

In the above example, we are having a button, when clicked will increment the count by 1. Then we have written a useEffect hook where we console log "Running useEffect" and update the title of the page (direct DOM manipulation) with the number of clicks.

If you run the code and open the browser console, you should be able to see the logs as shown below:

Simple UseEffect

As you could see, first the component will be rendered and then the effect will run. Now, if you click on the button, you will see that the component is rendered again (since the state has changed) and the title of the page is updated with the number of clicks.

Simple useEffect clicked

From this, we can infer that the useEffect (with only a callback function) will run after each render.

Infinite Loops

Since useEffect runs after every render, what if the effect inside useEffect causes the component to re-render? That is, if the useEffect updates the state of the component, wouldn't it cause the component to re-render? Wouldn't it cause the useEffect to run again, and so on causing an infinite loop? Yes!

Let's see it using an example:

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [count, setCount] = useState(0)
5
6 useEffect(() => {
7 console.log("Running useEffect")
8 setCount(count + 1)
9 })
10
11 console.log("Running render")
12 return (
13 <div className="App">
14 <button onClick={() => setCount(count + 1)}>Click Me</button>
15 </div>
16 )
17}
18
19export default App

If you open the console, you will see the code is executed indefinitely:

Infinite loop

If you look closely, React is showing a warning:

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

This clearly says that you are updating a state inside the useEffect, which is causing the component to re-render.

How to avoid infinite loops and still update the state inside the useEffect?

This is where the dependency array comes into the picture. We will learn about how to use them in the upcoming sections.

Fetching data with useEffect

Let's build a small app where we fetch the bitcoin price and display it. Before implementing the app, let's add some styles to index.css:

index.css
1body {
2 margin: 10px auto;
3 max-width: 800px;
4}
5.App {
6 display: flex;
7 flex-direction: column;
8 align-items: center;
9}
10
11.refresh {
12 display: flex;
13 align-items: center;
14}
15
16.refresh-label {
17 margin-right: 10px;
18}
19
20.switch {
21 position: relative;
22 display: inline-block;
23 width: 60px;
24 height: 34px;
25}
26
27.switch input {
28 opacity: 0;
29 width: 0;
30 height: 0;
31}
32
33.slider {
34 position: absolute;
35 cursor: pointer;
36 top: 0;
37 left: 0;
38 right: 0;
39 bottom: 0;
40 background-color: #ccc;
41 -webkit-transition: 0.4s;
42 transition: 0.4s;
43}
44
45.slider:before {
46 position: absolute;
47 content: "";
48 height: 26px;
49 width: 26px;
50 left: 4px;
51 bottom: 4px;
52 background-color: white;
53 -webkit-transition: 0.4s;
54 transition: 0.4s;
55}
56
57input:checked + .slider {
58 background-color: #2196f3;
59}
60
61input:focus + .slider {
62 box-shadow: 0 0 1px #2196f3;
63}
64
65input:checked + .slider:before {
66 -webkit-transform: translateX(26px);
67 -ms-transform: translateX(26px);
68 transform: translateX(26px);
69}
70
71/* Rounded sliders */
72.slider.round {
73 border-radius: 34px;
74}
75
76.slider.round:before {
77 border-radius: 50%;
78}

We will use the endpoint https://api.coincap.io/v2/assets/bitcoin to fetch the bitcoin price. Now if you are using async-await syntax to fetch the data, your code will look like:

1useEffect(async () => {
2 try {
3 const response = await fetch("https://api.coincap.io/v2/assets/bitcoin")
4 const result = await response.json()
5 const bitcoinPrice = (+result?.data?.priceUsd).toFixed(2)
6 setPrice(bitcoinPrice)
7 } catch (error) {
8 console.log("error", error)
9 }
10}, [])

If you use this code, you will get a warning from React telling us not to make useEffect callbacks async. How to tackle this problem? The error message itself suggests having another async function and call it inside the useEffect callback.

useEffect Async Await

So if we update our code accordingly it will look like the following:

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [price, setPrice] = useState()
5
6 useEffect(() => {
7 const fetchData = async () => {
8 try {
9 const response = await fetch("https://api.coincap.io/v2/assets/bitcoin")
10 const result = await response.json()
11 const bitcoinPrice = (+result?.data?.priceUsd).toFixed(2)
12 setPrice(bitcoinPrice)
13 } catch (error) {
14 console.log("error", error)
15 }
16 }
17 fetchData()
18 }, [])
19
20 return (
21 <div className="App">
22 <h2>{price && `Bitcoin Price: $${price}`}</h2>
23 </div>
24 )
25}
26
27export default App

You might observe that we are passing an empty array as a dependency (the second argument to useEffect). This is to ensure that the useEffect runs only once when the component is mounted and not when the component is updated or re-rendered. As you might have guessed correctly, useEffect with an empty dependency array is the same as that of componentDidMount lifecycle method in a class component.

Now if you run the app, you should be able to see the bitcoin price being displayed:

Bitcoin Price

Running it when certain states change

Since the bitcoin price changes every moment, let's make our app more interesting and fetch the price every 5 seconds!

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [price, setPrice] = useState()
5
6 useEffect(() => {
7 let interval
8 const fetchData = async () => {
9 try {
10 const response = await fetch("https://api.coincap.io/v2/assets/bitcoin")
11 const result = await response.json()
12 const bitcoinPrice = (+result?.data?.priceUsd).toFixed(2)
13 setPrice(bitcoinPrice)
14 } catch (error) {
15 console.log("error", error)
16 }
17 }
18 fetchData()
19
20 interval = setInterval(() => {
21 fetchData()
22 }, 5 * 1000)
23 return () => {
24 clearInterval(interval)
25 }
26 }, [])
27
28 return (
29 <div className="App">
30 <h2>{price && `Bitcoin Price: $${price}`}</h2>
31 </div>
32 )
33}
34
35export default App

As you may see, we have added a cleanup call back, which will clear the interval, so that it is cleared before the next render and does not run indefinitely and cause memory leakage. You will find more significance to this in the next section.

Now if you run the app and see the network tab, you will see the call happening every 5 seconds and the price getting refreshed:

Fetch Price Every 5 seconds

Let's not stop here, let's add a toggle button to turn off and on the auto refresh:

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [price, setPrice] = useState()
5 const [autoRefresh, setAutoRefresh] = useState(true)
6
7 useEffect(() => {
8 let interval
9 const fetchData = async () => {
10 try {
11 const response = await fetch("https://api.coincap.io/v2/assets/bitcoin")
12 const result = await response.json()
13 const bitcoinPrice = (+result?.data?.priceUsd).toFixed(2)
14 setPrice(bitcoinPrice)
15 } catch (error) {
16 console.log("error", error)
17 }
18 }
19
20 if (!price) {
21 // Fetch price for the first time when the app is loaded
22 fetchData()
23 }
24
25 if (autoRefresh) {
26 interval = setInterval(() => {
27 fetchData()
28 }, 5 * 1000)
29 }
30
31 return () => {
32 clearInterval(interval)
33 }
34 }, [autoRefresh, price])
35
36 return (
37 <div className="App">
38 <h2>{price && `Bitcoin Price: $${price}`}</h2>
39 <div className="refresh">
40 <div className="refresh-label">Auto refresh:</div>
41 <label className="switch">
42 <input
43 type="checkbox"
44 checked={autoRefresh}
45 onChange={e => {
46 setAutoRefresh(e.target.checked)
47 }}
48 />
49 <span className="slider round"></span>
50 </label>
51 </div>
52 </div>
53 )
54}
55
56export default App

As you can see we have added a state called autoRefresh, which will be set to true or false based on the toggle status of the slider. Also, we have added 2 conditions, one to check if the price is present or not and load the price when it is not present. Another, to check if the autoRefresh is enabled, then only run the logic to fetch price every 5 seconds. Since we need useEffect to be executed every time the value of price and autoRefresh changes, we have added it to the dependency array.

Auto Refresh

The cleanup function will get executed before the next render so that, when we set the autoRefresh to false, the interval will be cleared and data will not be fetched any further.

The difference between the cleanup function and componentWillUnmount is that the cleanup function runs before every re-render and componentWillUnmount runs only when the whole component is unmounted (towards the end of the component lifecycle). You can read more on why they are different here.

General trivia on useEffect

  • useEffect needs to be inside the functional component like any other React hook.
  • One component can have as many useEffect as required. React will make sure that they are clubbed together and executed (wherever possible).
  • Like how state variables can be part of the dependency array, you can have the props as well in the dependency array. Make sure that you are adding only the required dependencies, adding unnecessary dependencies will cause unwanted execution of the effect.
  • If you miss adding a dependency, react will show a warning to help you avoid bugs:
    Missing Dependency

Source code and demo

You can download the source code here and view a demo here.

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com