Why is useEffect running twice?

Viewed 3185
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?

3 Answers

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.

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>
Related