React.StrictMode is a development-only component that enables additional checks and warnings to help you detect potential problems in your code. It has zero impact in production.
Basic usage:
1import { StrictMode } from "react";23function App() {4 return (5 <StrictMode>6 <MyApp />7 </StrictMode>8 );9}
What StrictMode does:
1. Double-invokes render functions (in development): React calls your component function twice during development to detect impure renders:
1function Counter() {2 const [count, setCount] = useState(0);34 // BAD: side effect in render (StrictMode will warn)5 if (count === 0) {6 setCount(1); // Setting state during render!7 }89 return <div>{count}</div>;10}
2. Double-invokes useEffect cleanup/setup: In development, StrictMode runs the effect, then immediately runs its cleanup, then runs the effect again. This ensures your effects properly clean up:
1function Timer() {2 useEffect(() => {3 const timer = setInterval(() => console.log("tick"), 1000);4 // StrictMode runs this cleanup immediately after setup5 return () => clearInterval(timer);6 }, []);7}
3. Detects unsafe lifecycle methods: Warns about deprecated class component lifecycle methods that can cause bugs.
4. Warns about legacy string refs:
Encourages using useRef or createRef instead of string refs like ref="myRef".
5. Detects deprecated APIs:
Warns about using ReactDOM.render instead of createRoot.
Why double invocation happens:
Code — detecting side effects:
1function DataLoader() {2 // BAD: side effect in render3 const data = heavyComputation(); // Pure function — no side effects!4 console.log(data); // Side effect in render — StrictMode warns56 // GOOD: move side effects to useEffect7 useEffect(() => {8 console.log(data);9 }, [data]);1011 return <div>{JSON.stringify(data)}</div>;12}
Best practice: Always wrap your app in <StrictMode> during development. Remove it only if you have a specific reason (which is rare).