Why is useEffect running twice? [duplicate]
Asked Answered
N

4

13
import { useContext, useEffect, useState } from 'react';

const Log =  ()  =>  {
    useEffect(()  => {
        console.log('Running ...')
    },[])

    return(<p>here</p>)

}

export default Log;

Whenever this code runs, I get Running... messages twice in the browser console.

I think it should run once, as I have an empty second parameter in useEffect.

Can anybody explain why it is getting run twice?

Np answered 24/5, 2022 at 21:58 Comment(3)
It depends on the context. Most likely it's something up on the tree.Idiophone
Sounds like you have <StrictMode> enabled?Astragal
Does this answer your question? React 18, useEffect is getting called two times on mountGeddes
A
38

This is due to <StrictMode> most likely in your root tree.

What is strict mode?

StrictMode is a tool for highlighting potential problems in an application.

How does it make useEffect() run twice?

It activates additional checks and warnings for its descendants, or in other words... renders twice.

Note: Strict mode checks are run in development mode only; they do not impact the production build.

Americanist answered 24/5, 2022 at 22:21 Comment(1)
For a more detailed answer visit https://mcmap.net/q/64783/-why-useeffect-running-twice-and-how-to-handle-it-well-in-reactEsbjerg
G
2

You can prevent running useEffect() twice by using the following way,

import { useEffect, useRef } from 'react';
const Log = () => {
    // initiate dataFetch
    const dataFetch = useRef(false)

    useEffect(() => {
        console.log('Running ...')

        // start:: prevent executing useEffect twice
        if (dataFetch.current)
            return
        dataFetch.current = true
        // end:: prevent executing useEffect twice
    }, [])

    return (<p>here</p>)
}

export default Log;
Goldner answered 18/1, 2023 at 10:14 Comment(0)
R
1

If useEffect doesn't have any dependencies, the component itself is called only once.

This answer will help you.

React Hooks: useEffect() is called twice even if an empty array is used as an argument

Rodrich answered 25/5, 2022 at 0:41 Comment(0)
R
1

As the dependency list of useEffect() sets empty, "console.log" will automatically run whenever the Log component re-renders.
I think there might be some changes of context or parent component from component tree.
Please check your project structure.

<ContextProvider.Provider value={setGlobalState}>
  <ParentComponent>
    <Log/>
  </Parent Component>
</ContextProvider.Provider>
Ruella answered 25/5, 2022 at 3:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.