React·100 questions

What is StrictMode and why might effects be called twice in dev?

Answer

StrictMode in React often surprises developers, especially when they notice that component effects run twice upon mounting. It is important to understand that StrictMode is a static and dynamic analysis tool that works exclusively in development mode and is automatically disabled in the production build.

The main purpose of StrictMode is to help developers proactively identify potential problems, memory leaks, and unwanted side effects in components. Modern React is moving toward the concept of concurrent rendering, where components can interrupt, suspend, and restart. Double-calling effects in development mode simulates behavior where a component mounts, immediately unmounts, and mounts again to verify resource cleanup correctness.

If your effects trigger incorrectly or cause duplicate requests upon being called twice, it indicates architectural issues in the code that will definitely manifest in production under certain conditions. This is why you should never disable StrictMode just to get rid of duplicate logs or requests.

To work correctly with effects under StrictMode, follow these principles:

Write functions inside the useEffect hook strictly idempotent so that re-running them does not cause bugs.
Always return a cleanup function that cancels subscriptions, timers, or network requests.
Ensure effect dependencies are specified correctly and do not create infinite rendering loops.
Remember that the double run only occurs in development mode and does not affect production performance.
Treat StrictMode warnings and features as useful hints for writing cleaner code.
Was this answer helpful?

More questions in this topic

Related questions from other topics