Open In App

How to Fix React useEffect running twice in React 18 ?

In React applications, the useEffect hook is commonly used for handling side effects, such as data fetching, subscriptions, or manually changing the DOM. However, encountering the issue of useEffect running twice can lead to unexpected behavior and impact the performance of your application. In this article, we'll explore various approaches to resolve this error and provide examples for each approach.

Steps to Create React Application

Step 1: Create a React application using the following command:

npm create vite@latest

Step 2: Provide the Project name and move to the root directory using the below command.

cd <foldername>

Step 3: In the directory of the project write a command in the terminal to install the dependency.

npm install

Why useEffect is running twice?

The useEffect hook in React is designed to execute side effects in function components. However, if not used correctly, it might run multiple times, leading to unexpected behavior in your application.

import { useEffect } from "react"
function App() {
    useEffect(() => {
        console.log("Calling GFG by use effect")
    }, [])
    return (
        <>
            <h1 className="gfg">Geeks for Geeks </h1>
        </>
    )
}

export default App

Output:

error

Approaches for Resolving the Error

Steps to Solve useEffect Running Twice

stricktmod

Fig :- Restrict mode in react

Screenshot2024-04-3019014

Fig :- Console after removing of Strict mode

Some other reasons are as follows

More possible approached to prevent useEffect running twice

Article Tags :