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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With