Home > OS >  Why useEffect is running twice?
Why useEffect is running twice?

Time:05-25

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

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

    return(<p>here</p>)

}

export default Log;

When ever this code runs, I get Running... messages twice in console of browser.

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

Can anybody explain it why is it getting run twice?

CodePudding user response:

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.

CodePudding user response:

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

  • Related