Why does an effect run twice in development?
Model answer
In StrictMode, React intentionally mounts, unmounts and mounts components again in development to help you find effects that are not cleaned up properly. It does not happen in production.
If running twice breaks your code, the fix is a proper cleanup function (abort the fetch, remove the listener), not removing StrictMode.
Learn this topic
React useEffect Explained: Side Effects, Dependencies and Cleanup in the course React.js Full Course: Beginner to Advanced.
Sign in to add your own answer.
More questions
- What are hooks, and what are the rules of hooks?
- What does useEffect do?
- What does the dependency array of useEffect mean?
- What is the cleanup function in useEffect, and when does it run?
- How do you fetch data in a React component with useEffect?
- What are race conditions in effects and how do you prevent them?