React useEffect() Hook: Structure, Usage, Examples & Tips
Updated on Feb 14, 2025 | 10 min read | 56.2k views
Share:
For working professionals
For fresh graduates
More
Updated on Feb 14, 2025 | 10 min read | 56.2k views
Share:
Table of Contents
In recent times, React has become the most popular JavaScript Library. It has gained a strong community around it due to its robustness and ease of use. React makes it easy to create interactive UIs and smooth user experiences. Enough about React; I am sure you are already aware of it, which is why you’ve landed on this article. Let’s come to the point and discuss today’s topic, react useEffect hook.
Hooks are a new addition to React 16.8. They let you use the state and other React functionalities without writing an ES6 class for it. Thereby, hooks have made the use of functional components rather easier than class-based components, which has taken the whole community by amazement! Avid developers like you can pick a detailed tutorial on React Native course and hone your expertise in App development.
useEffect hook is part of React’s Hooks API. The core principle of this hook is to let you perform side effects in your functional components. The useEffect hook is a smooth combination of React’s lifecycle methods like componentDidMount, componentDidUpdate and componentWillUnmount. According to React documentation, the useEffect hook was developed to overcome some challenges posed by the life cycle methods of ES6 class components.
Sometimes, we want to run some code after the DOM has been updated. It can be anything, showing pop-ups, sending API requests, logging users’ information etc. and such functions don’t require cleanup to be performed. They are just hit-once functions and then we forget about them. Such places are the best examples to use the useEffect hook.
You can learn more about Mobile App Development course, which has in-depth explanations of the core concepts of React. Let’s now continue on the useEffect, don’t forget to check out the link though.
// onMount
useEffect(() => {
console.log("I Only run once (When the component gets mounted)")
}, []);
The useEffect hook is used to manage side effects in functional components including requesting data, changing the DOM, and creating subscriptions or timers. It mimics the lifecycle functions of class-based components. The aim for introducing useEffect Hook is to eliminate the side effects of employing class-based components.
For example, operations like as changing the DOM, obtaining data from API endpoints, configuring subscriptions or timers, and so on might cause unintended consequences. Because the render function generates side effects too quickly, life cycle techniques must be used to examine them.
The React useEffect hook, a crucial part of React's functional component arsenal, offers a streamlined way to manage side effects. Comprising a distinct structure, it allows developers to incorporate asynchronous operations, data fetching, subscriptions, or any code that requires React useEffect() cleanup. The fundamental syntax involves passing a function and, optionally, an array of dependencies.
useEffect(() => {
// Side effect logic
return () => {
// Cleanup logic
};
}, [dependency1, dependency2]);
Explanation:
Imagine a scenario where data fetching is the side effect:
useEffect(() => {
const fetchData = async () => {
const result = await axios.get('https://api.example.com/data');
setData(result.data);
};
fetchData();
}, [dependency]);
Significance of Parameters:
Mastering the structure and parameters of React useEffect hook empowers developers to handle asynchronous operations with finesse, ensuring efficient and controlled side effects within React functional components.
The react useEffect Hook essentially replaces every single lifecycle function that you may run into.
useEffect(() => {
// Update the document title using the browser API document.title = `You clicked ${count} times`;
});
This snippet is based on a counter-example in which we are setting the document title to a custom message, including the number of clicks. Fetching data, setting subscriptions, and manually modifying the DOM in React components are examples of side effects. Whether or not you're used to calling these operations "side effects", you've probably done them before in a component.
We know that useEffect() is used to cause side effects in functional components, and it can also handle the componentDidMount(), componentDidUpdate(), and componentWillUnmount() life-cycle methods of class-based components within functional components.
useEffect(()=>{
//You can add your code here for mounting phase of component
console.log("Mounting in Functional Component")
},[])
// adding an empty array ensures that the useEffect is only triggered once
// (when the component mounts)
useEffect(()=>{
//You can add your code for updating phase of component
console.log("Updating in Functional Component")
},[values])
//values triggers re render whenever they are updated in your program,
//you can add multiple values by separating them by commas
useEffect(()=>{
return()=>{
//You can add your code for unmounting phase of component
console.log("Functional Component Removed ")
}
},[])
useEffect takes two arguments. The first argument passed to useEffect is a function called effect and the second argument (optional) is an array of dependencies. Below is an example.
import { useEffect } from "react";
import { render } from "react-dom";
const App = (props) => {
useEffect(() => {
console.log("Effect ran");
}); //No second Argument
return <h1> upGrad! </h1>;
};
const root = document.getElementById("root");
render(<App />, root);
The effect runs when the component is mounted, and whether or not it runs on subsequent updates is determined by an array of dependencies passed as the second argument to react useEffect.
Effects take no parameters, and the useEffect return function returns either a function or undefined. If the useEffect return function returns a function, the returned function is called cleanup. cleanup is run before the effect is reached (to clean up effects from previous renders). If you want to learn more about why and when to clean up, check out the Best React online course. useEffect returns either a function or undefined, so it's not uncommon to see effects that haven't been cleaned up.
The second argument of useEffect is an array of dependencies. If you want to control when the effect runs after the component has been mounted, pass an array of dependencies as the second argument. Dependencies are values defined outside useEffect but used inside useEffect, such as:
function App(){
// state
const[state, setState] = useState(0);
useEffect(() => {
console.log(state);
// since we are using state, we have to pass it as a dependency
}, [state])
}
React will compare the current value of the constraint with the value from the previous render. If they are not equal, the effect is called. This argument is optional. If omitted, the effect will run after each render. You can pass an empty array if you only want the effect to run on the first render.
useEffect(() => {
console.log("Effect ran");
}, []) // the useEffect will now only be evoked once per render
Dependencies can be states or props. Note that values defined inside a component outside of useEffect must be passed as dependencies when used inside useEffect. This is illustrated below.
function App() {
const [count, setCount] = useState(1);
// count is defined in App, but outside of useEffect
useEffect(() => {
//since we are using count, we have to pass it as a dependency
console.log(count);
}, [count])
}
The output will be the count value and if the count value changes it will be the changed value as we are using count as the dependency.
If I define a function outside useEffect and call it inside the effect, should I pass it as a dependency?
The following is a react useEffect example:
function App(){
const [data, setData] = useState(null);
const fetchData = () => {
// some code
}
useEffect(() => {
fetchData(); //used inside useEffect
}, [fetchData])
}
It is not recommended to define a function outside and call it inside an effect. In the above case, the passed dependency is a function, and a function is an object, so fetchData is called on every render. React compares the fetchData from the previous render and the current render, but the two aren't the same, so the call is triggered.
The useEffect in react js allows you to perform side effects in your components. The react useEffect examples of side effects include retrieving data, direct DOM updates, and timers. The second argument is optional.
useEffect(<function>, <dependency>)
Now that we are clear with the core concept of the useEffect hook, the question arises of when and how to use this hook. Following are 4 major use-cases where we use the useEffect hook. Before proceeding to the use cases, I would like you to go through a course that will not only help you get through many core concepts of App development but also provide you with the Mobile App Development certification online that adds a shining star to your resume, do check it out.
You can make use of the useEffect hook in a similar fashion to what the componentDidMount function did in class-based components. Usually, adding listeners, fetching initial data, etc., are the actions executed when the component is mounting. This is easily achieved by useEffect; the only thing you need to make sure of is that you have to pass the dependency array as empty. If there are no dependencies that means it will remain the same all the time.
To call the useEffect function on every component render, skip adding the dependency list. When the dependency list is not present, react will have nothing to compare the previous value with; as a result, the effect will run every time.
To call the useEffect functionality based on any condition, we have to specify the list of dependencies. And the thumb rule is always to add those dependencies that you are using inside the useEffect().
To clean up the mounting actions like removing event listeners or stopping data fetching with a side effect we call the useEffect after the component unmounts. A return statement with a function should be added inside the useEffect() hook.
// use of useEffect in react for every rerender
useEffect(() => {
console.log("I run every time this component re-renders")
});
//use of useEffect in react for onMount
useEffect(() => {
console.log("I Only run once (When the component gets mounted)")
}, []);
// Condition-based
useEffect(() => {
console.log("I run every time my condition is changed")
}, [condition]);
// Condition based with "clean up"
useEffect(() => {
console.log("I run every time my condition is changed")
return () => {
console.log("Use this return as a 'clean up tool' (this runs before the actual code)")
}
}, [condition]);
Sometimes we want to execute additional code after React updates the DOM. Network requests, manual DOM mutations, and logging are common examples of effects that don’t require cleanup. Because we can do them and quickly forget them. Here's an example useEffect hook that relies on a variable, If the count variable updates, the effect will run again:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count * 2);
}, [count]);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);
Earlier, we saw how to express side effects that don't require cleanup. However, some effects do. For example, in the below code, suppose we are using the below useEffect hook for an input field so that when a character is typed in the input field, an alert is shown after 1 second. But if the user doesn't wait for 1 second and types multiple letters in the input field, then cleanup is required to clean the previous alerts, which were to happen, and only the most recent alert will be called.
useEffect(() => {
let isCancelled = false;
const changeHandler = async () => {
await timeout(1000);
if (!isCancelled) {
alert(`A name was changed: ${value}`);
}
};
changeHandler();
//The cleanup function is called when useEffect is called again or on unmount.
return () => {
isCancelled = true;
};
}, [value]);
Let's use a timer as an example. We will use setTimeout() to count 1 second after the initial render:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Wait a second! ! It should only count once, but it keeps counting! react hooks useEffect runs on every render. In other words, when the counter changes, it renders and triggers another effect. we don't want that. There are several ways to control when side effects occur. You should always include a react useEffect second argument parameter that accepts an array. You can optionally pass dependencies to useEffect in this array. We can use an empty array to tackle this issue like this:-
useEffect(() => {
//only runs on the first render
}, []);
So to solve this problem, we only run this effect on the first render. Only run the effect on the first render.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
}, []); // empty array
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Want more insights, check out the best React online course.
By adhering to these tips, you can harness the full potential of `useEffect` in React, ensuring efficient, well-controlled, and bug-free side effects within your functional components.
Understanding the design concepts and best practices underlying React useEffect hooks is an important skill to acquire if you want to become a next-level React developer.
If you started your React journey before 2025, you need to throw away the instinct of thinking about lifecycle methods and instead start thinking about React useEffect. Adopting a mental model of effects will get you familiar with component life cycles, data flow, and other hooks (useState, useRef, useContext, etc.).
Unlock new possibilities with our popular Software Engineering Courses. Check out the programs below to find your ideal match.
Explore the world of technology with our free Software Development Courses. Choose from the options below to find your perfect fit.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources