Understanding ReactJs useEffect Hook
Table of Contents
- What is useEffect Hook in ReactJS?
- How does the React useEffect hook work?
- Test your knowledge with a quick quiz!
What is useEffect Hook in ReactJS?
The main purpose of using useEffect Hook is to allow you to perform side effects in your components. For example, tasks like updating the DOM, fetching data from API end-points, setting up timers or subscriptions.
How does the React useEffect hook work?
It accepts two arguments. The second argument is optional.
useEffect(, )
Let’s consider an example for setting up timers.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
return
<h1>I've rendered {count} times</h1>
;
}
ReactDOM.render(, document.getElementById('root'));
In the above example, useEffect runs on every render. Whenever the count changes, a render happens and triggers another effect.
But you wouldn’t want this to happen. Including the second parameter can resolve the problems here.
When no dependency is passed
useEffect(() => {
//Runs on every render
});
When there’s an empty array
useEffect(() => {
//Runs only on the first render
}, []);
When props or state values are passed
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
This issue can be fixed; you must run the effect only on the initial render.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
} []); // <- add empty brackets here
return
<h1>I've rendered {count} times!</h1>
;
}
ReactDOM.render(, document.getElementById('root'));
In the following example of useEffect Hook, the function is dependent on a variable. This means that the effect will run again when the count variable updates.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count * 2);
}, [count]); // <- add the count variable here
return (
<>
Count: {count}
<button>setCount((c)=> c+1)}>+</button>
Calculation: {calculation}
</>
);
}
ReactDOM.render(, document.getElementById('root'));
Effects with Cleanup
Some effects in React require cleanup. For example, when effects like timeouts and subscriptions are no longer needed, they should be disposed of.
Adding a return function towards the end will do this job. In the following example, the timer is cleaned up at the end of the useEffect Hook.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
return () => clearTimeout(timer)
}, []);
return
<h1>I've rendered {count} times!</h1>
;
}
ReactDOM.render(, document.getElementById("root"));
Test your knowledge with a quick quiz!
What does empty dependency list ( [ ] ) mean?
Select the correct answer