11
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?

Boann
  • 48,794
  • 16
  • 117
  • 146
Shu.T
  • 439
  • 1
  • 6
  • 12

4 Answers4

34

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.

gavin
  • 1,224
  • 5
  • 17
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

Maradox
  • 620
  • 2
  • 13
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>
StormyTalent
  • 216
  • 1
  • 11
1

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;
Sourav Das
  • 527
  • 2
  • 5
  • 13