How to Implement Strict Mode in React

React Strict Mode is a development-only tool that helps developers write better React code by highlighting potential problems in an application. This article provides a straightforward guide on how to implement Strict Mode in your React projects, explains its core benefits, and demonstrates how it behaves during development.

What is React Strict Mode?

Strict Mode is a helper component in React that analyzes your component tree during development. It does not render any visible UI. Instead, it activates additional checks and warnings for its descendants, helping you catch common bugs early in the development cycle. Key benefits include:

Implementing Strict Mode in React

Implementing Strict Mode is simple. You wrap your application, or a specific part of it, with the <React.StrictMode> tag.

1. Implementing in React 18+

In modern React applications (React 18 and newer), Strict Mode is usually set up by default in the main entry file (typically index.js or main.jsx). Here is how you implement it manually:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

2. Implementing in React 17 and Older

For older React applications using the legacy rendering API, the implementation is highly similar but uses the older render method:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

3. Applying Strict Mode Partially

You do not have to apply Strict Mode to your entire application all at once. If you are working on a large, legacy codebase, you can run Strict Mode on specific components to fix issues incrementally:

import React from 'react';
import Header from './Header';
import LegacyComponent from './LegacyComponent';
import ModernComponent from './ModernComponent';

function App() {
  return (
    <div>
      <Header />
      {/* This component will not run in Strict Mode */}
      <LegacyComponent /> 
      
      {/* Only this component and its children will run in Strict Mode */}
      <React.StrictMode>
        <ModernComponent />
      </React.StrictMode>
    </div>
  );
}

Important Things to Keep in Mind