Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is useEffect running twice? [duplicate]

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?

like image 894
Shu.T Avatar asked Feb 16 '26 03:02

Shu.T


2 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.

like image 174
Gavin Holmes Avatar answered Feb 18 '26 17:02

Gavin Holmes


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;
like image 33
Sourav Das Avatar answered Feb 18 '26 18:02

Sourav Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!