Table of Contents
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 usingsetInterval
.
The syntax
useEffect
has the following syntax:
1useEffect(2 () => {3 // the callback function which has the side effect you want to run4 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
.
useEffect
The simplest Since the only mandatory parameter of an useEffect
is the callback function, let's write one with just the callback:
1import { useEffect, useState } from "react"23function App() {4 const [count, setCount] = useState(0)56 useEffect(() => {7 console.log("Running useEffect")8 document.title = `You clicked ${count} times`9 })1011 console.log("Running render")12 return (13 <div className="App">14 <button onClick={() => setCount(count + 1)}>Click Me</button>15 </div>16 )17}1819export 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:
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.
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:
1import { useEffect, useState } from "react"23function App() {4 const [count, setCount] = useState(0)56 useEffect(() => {7 console.log("Running useEffect")8 setCount(count + 1)9 })1011 console.log("Running render")12 return (13 <div className="App">14 <button onClick={() => setCount(count + 1)}>Click Me</button>15 </div>16 )17}1819export default App
If you open the console, you will see the code is executed indefinitely:
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.
useEffect
Fetching data with 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
:
1body {2 margin: 10px auto;3 max-width: 800px;4}5.App {6 display: flex;7 flex-direction: column;8 align-items: center;9}1011.refresh {12 display: flex;13 align-items: center;14}1516.refresh-label {17 margin-right: 10px;18}1920.switch {21 position: relative;22 display: inline-block;23 width: 60px;24 height: 34px;25}2627.switch input {28 opacity: 0;29 width: 0;30 height: 0;31}3233.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}4445.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}5657input:checked + .slider {58 background-color: #2196f3;59}6061input:focus + .slider {62 box-shadow: 0 0 1px #2196f3;63}6465input:checked + .slider:before {66 -webkit-transform: translateX(26px);67 -ms-transform: translateX(26px);68 transform: translateX(26px);69}7071/* Rounded sliders */72.slider.round {73 border-radius: 34px;74}7576.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.
So if we update our code accordingly it will look like the following:
1import { useEffect, useState } from "react"23function App() {4 const [price, setPrice] = useState()56 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 }, [])1920 return (21 <div className="App">22 <h2>{price && `Bitcoin Price: $${price}`}</h2>23 </div>24 )25}2627export 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:
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!
1import { useEffect, useState } from "react"23function App() {4 const [price, setPrice] = useState()56 useEffect(() => {7 let interval8 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()1920 interval = setInterval(() => {21 fetchData()22 }, 5 * 1000)23 return () => {24 clearInterval(interval)25 }26 }, [])2728 return (29 <div className="App">30 <h2>{price && `Bitcoin Price: $${price}`}</h2>31 </div>32 )33}3435export 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:
Let's not stop here, let's add a toggle button to turn off and on the auto refresh:
1import { useEffect, useState } from "react"23function App() {4 const [price, setPrice] = useState()5 const [autoRefresh, setAutoRefresh] = useState(true)67 useEffect(() => {8 let interval9 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 }1920 if (!price) {21 // Fetch price for the first time when the app is loaded22 fetchData()23 }2425 if (autoRefresh) {26 interval = setInterval(() => {27 fetchData()28 }, 5 * 1000)29 }3031 return () => {32 clearInterval(interval)33 }34 }, [autoRefresh, price])3536 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 <input43 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}5556export 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.
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:
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!