React Strict Mode Cheat Sheet
What Is React Strict Mode?
React Strict Mode is a development-only tool used to:
- Highlight potential issues in your React code
- Enforce best practices
- Help identify unsafe lifecycles and side effects
It does not render anything to the DOM and has no effect in production builds.
How to Enable Strict Mode
Wrap part or all of your app with <React.StrictMode>
:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
You can wrap multiple components or just isolate new features.
What It Does (and Why It Matters)
Strict Mode helps with:
Feature | Benefit |
---|---|
Identifying unsafe lifecycles | Warns about deprecated lifecycle methods like componentWillMount |
Detecting unexpected side effects | Runs effects (like useEffect ) twice to catch issues |
Detecting legacy ref API usage | Alerts when using string refs |
Preventing obsolete patterns | Encourages modern, stable React patterns |
Highlighting unexpected behavior | Reveals issues early in development |
Double Invocation: Why Effects Run Twice
In development, React intentionally runs useEffect
and other lifecycle methods twice (only in Strict Mode).
This catches:
- Non-idempotent functions (functions that behave differently each time)
- Async race conditions
- Side effects that shouldn't repeat
To fix this:
- Avoid side effects in render
- Clean up effects properly
useEffect(() => {
const timer = setTimeout(() => console.log('Running...'), 1000);
return () => clearTimeout(timer); // cleanup avoids duplication
}, []);
Best Practices with React Strict Mode
- Always use in development. Helps future-proof your code.
- Test side-effect logic. Ensure effects are idempotent.
- Avoid legacy lifecycle methods. Migrate to
useEffect
oruseLayoutEffect
. - Use cleanup functions. Especially with timers, subscriptions, or event listeners.
- Don't panic about the double execution. It's by design—just write cleaner code.
When to Avoid Strict Mode
- When debugging tools or third-party libraries behave inconsistently under double-invoked effects.
- For performance testing—Strict Mode adds overhead that doesn't reflect production behavior.
Summary: Why Use React Strict Mode?
React Strict Mode:
- Surfaces bugs early
- Makes refactors safer
- Promotes cleaner, more stable code
- Helps you follow React development best practices
Pro tip: Keep Strict Mode on during all local development. You’ll thank yourself later.