I have this _app.tsx
function MyApp({ Component, pageProps }: AppPropsWithLayout) {
useEffect(() => {
store?.dispatch(me({}))
}, [])
I see in network tab me
get called 2 times. If I comment it, then 0 times. Why? I thought []
ensure, only once the useEffect
will get called.
This was answered many times on StackOverflow. One of them is here: https://stackoverflow.com/a/73321206/15814542
You can find the explanation here https://beta.reactjs.org/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development
React intentionally remounts your components in development to help you find bugs like in the last example. The right question isn’t “how to run an Effect once”, but “how to fix my Effect so that it works after remounting”.
Usually, the answer is to implement the cleanup function. The cleanup function should stop or undo whatever the Effect was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the Effect running once (as in production) and a setup → cleanup → setup sequence (as you’d see in development).