How useEffect works in ReactJS ?
Last Updated :
09 Oct, 2024
The useEffect hook in React is used to handle the side effects in the functional components. It allows us to perform operations like data fetching, subscriptions, and manual DOM updates. It runs on every re-render which can be controlled using the dependency array.
Syntax:
useEffect(() => {
// Side effect logic
return () => {
// Optional cleanup function
};
}, [dependencies]);
Parameter:
- Effect function: Function containing the side effect code.
- Dependency array: Contains dependencies to control the effects.
Return:
Optionally returns a cleanup function to clear the resources or processes before unmount and re-render.
How useEffect Works?
useEffect executes the code on every render and asloThe working of useEffect involves 3 steps
Mounting
It is the pahse when the component is added to the DOM, resulting in the first render of the ui. And on mounting, useEffect executes the code defined such as data fetching, animations etc.
Updating
This phase triggers when any od the component state and prop changes and the component is re-rendered. As useEffectr runs on every render it execures the sideeffects. It can be controlled with the dependency array.
Unmounting or Cleanup
This phase involves removing the componet from the dom. At this time the useEffect returns a function. This cleanup function is executed during unmount to remove the side effects like event listeners, timers and networking tasks.
So, When we want to perform something after each render of component then we can use the useEffect() hook. By using this Hook, we tell React that our component needs to do something after render by passing a function. React remember the function we passed in useEffect() hook and call it later after performing the DOM updates.
Steps to Create React Application
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure:
It will look like the following.

Example: This example demonstrates a component that displays an alert every time a button is clicked, showing the updated click count using the useEffect hook
JavaScript
// Filename - App.js
import React, { useState, useEffect } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
alert(`You clicked ${count} times`);
});
const handleUpdate = () => {
setCount(count + 1);
};
return (
<div>
<div>You have clicked {count} times</div>
<button onClick={handleUpdate}>Click me</button>
</div>
);
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Explanation: As we can from the above example whenever we update the state, React re-render the component, and just after that useEffect() hook call function that we have passed.
Similar Reads
ReactJS useEffect Hook
The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is
4 min read
ReactJS useLayoutEffect Hook
The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
2 min read
How React Works?
React is a tool made by Facebook to help create user interfaces, especially for single-page applications where the interface changes often and data updates a lot. It lets developers build reusable pieces of the interface, each managing its own state, which makes apps more efficient and simpler to ma
10 min read
How React Redux Works?
Redux is a predictable state container for JavaScript apps. It helps manage the state of an application in a consistent and predictable way. By centralizing the state, Redux makes it easier to debug and maintain applications, especially as they grow in complexity.Prerequisites NodeJSNPMReactJSWhy Do
6 min read
How React and ReactDOM works?
When you work with React, it is more than likely that you will build your apps with JSX. The JSX is a tag-based JavaScript syntax like looks familiar with HTML. React element is the atomic and most basic unit that you need to master before JSX and before moving forward with React. Note: In order to
9 min read
ReactJS useRef Hook
The useRef Hook is a built-in React Hook that returns a mutable reference object (ref) that persists across renders. Unlike state variables, updating a ref does not trigger a component re-render.Syntaxconst refContainer = useRef(initialValue);useRef returns an object { current: initialValue }.The .c
3 min read
Effect Management with useEffect Hook in React
useEffect serves as a foundational tool in React development, enabling developers to orchestrate side effects within functional components systematically. It facilitates the management of asynchronous tasks, such as data fetching and DOM manipulation, enhancing code organization and maintainability.
3 min read
How To Call Loading Function With React useEffect?
The useEffect runs by default after every render of the component. When placing useEffect in our component we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates. If we pass only a callback, the callback will run af
2 min read
React useInsertionEffect Hook
React useInsertionEffect Hook is used in React 18 to insert elements like dynamic styles, into the DOM before the layout effects are fired. This hook is mainly created to run on the client side, which makes it perfect for situations where the pre-layout element insertion is important. Syntax:useInse
3 min read
Why useLayoutEffect Hook is beneficial in React ?
useLayoutEffect is a React Hook that is similar to useEffect, but it fires synchronously after all DOM mutations. It's typically used for imperative DOM mutations or measurements, where you need to be sure that the DOM is updated before continuing. Here's an example of how you might use useLayoutEff
2 min read