In React, React.StrictMode
is a tool designed for highlighting common mistakes and potential problems in your application. It is not a component that renders anything visible to the user. Instead, it is used as a wrapper around your application’s root component to enable strict mode checks during development.
Here’s an example of how you can use React.StrictMode
in your App.js
file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
In this example:
- Import
React
andReactDOM
from thereact
library. - Import your main
App
component from theApp.js
file. - Wrap
<App />
with<React.StrictMode>
in theReactDOM.render
method.
Using React.StrictMode
provides the following benefits during development:
- Identifying Unsafe Lifecycles:
It helps to identify and log unsafe lifecycle methods, allowing you to update your code to use safer alternatives. - Detecting Legacy String Refs:
It warns about the usage of string refs, which are considered legacy. It encourages using thecreateRef
API or callback refs instead. - Warning about Deprecated FindDOMNode:
It issues a warning if thefindDOMNode
method is used.findDOMNode
is considered legacy, and alternative approaches should be used. - Detecting Legacy Context API:
It warns about the usage of legacy context API methods, encouraging the adoption of the new context API. - Identifying Unexpected Side Effects:
It helps to identify components with unintended side effects during the rendering phase.
Remember that the warnings and checks performed by React.StrictMode
are only active in development mode and are meant to assist developers in writing cleaner, safer React code. They are not present in the production build for performance reasons.
While using React.StrictMode
is beneficial during development, you may choose to remove it in the production build to avoid unnecessary overhead. It’s a helpful tool for catching potential issues early in the development process.
React.StrictMode in React is a tool that is used to provide potential problems in applications like Fragment. if there is any visible UI(User interface) then React.StrictMode does not render.
React.StrictMode provides additional checks and warning for its descendants. when we start our first project of React then in App.js we can see that React.StrictMode is in use.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
For more detail go to the official documentation of React