StrictMode is a tool for highlighting potential problems in your application. Like fragments, StrictMode does not render any visible UI. It triggers additional checks and warnings for its descendant elements.
Note: Strict mode checking is only run in development mode; They do not affect production builds.
You can enable strict mode for any part of your application. Such as:
import React from 'react';
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
);
}
Copy the code
In the example above, strict schema checking is not run on the Header and Footer components. However, ComponentOne and ComponentTwo and all their descendants will be checked.
StrictMode currently helps:
- Identify unsafe lifecycles
- Warning about using the outdated string REF API
- Warning about using the deprecated findDOMNode method
- Detect unexpected side effects
- Detect stale context APIS
- Future React releases will add more additional features.
When Strict mode is enabled, React lists all class components that use unsafe lifecycle methods and prints a warning message containing information about these components, as shown below:
Strict Mode Unsafe lifecycles warning Addressing issues identified by strict mode in the project at this time will make it easier to use concurrent rendering in future React releases.
Render phase lifecycles include the following class component methods:
constructor
componentWillMount
(or UNSAFE_componentWillMount)componentWillReceiveProps
(or UNSAFE_componentWillReceiveProps)componentWillUpdate
(or UNSAFE_componentWillUpdate)getDerivedStateFromProps
shouldComponentUpdate
render
setState
updater functions (the first argument) Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be non-deterministic.
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate methods Class component static getDerivedStateFromProps method Function component bodies State updater functions (the first argument to setState) Functions passed to useState, useMemo, or useReducer
Note: This only applies to development mode. Life cycles are not called twice in production mode.