- Published on
Why does React App run useEffect twice?
- Authors
- Name
- Ibtesum Reza Aninda
- @IbtesumAninda
From version 18 of React, if we use create-react-app to create React application, it runs the useEffect hook twice. For example:
useEffect(() => {
console.log('Hey there')
}, [])
The console will show the following:
Hey there
Hey there
If we fetch data from an API or do any other functions inside the useEffect hook, it runs the function twice. This behavior is also applicable in the case of useMemo or useReducer hooks.
The main reason for this weird behavior is StrictMode
in React. By default it is enabled in React, like the example below:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
const root = createRoot(document.getElementById('root'))
root.render(
<StrictMode>
<App />
</StrictMode>
)
We can disable StrictMode, but the official React documentation does not recommend it. StrictMode is a development tool, it doesn't affect the production. The components in React will be mounted, unmounted, and mounted once again if Strict Mode is enabled.
React prefers its components to be Pure Functions
. Strict mode enables it to fix bugs caused by impure rendering.
For more details, check out the current version of React documentation here