23
React Strict Mode - Good Parts Only
StrictMode
is a tool for highlighting potential problems in an application. Like Fragment
, StrictMode
does not render any visible UI. It activates additional checks and warnings for its descendants.
Example:
import React from 'react';
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
);
}
In the above example, strict mode checks will not be run against the Header
and Footer
components. However, ComponentOne
and ComponentTwo
, as well as all of their descendants, will have the checks.
đź’ˇ Note:
Strict mode checks are run in development
mode only
; they do not
impact the production build
.
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
, andshouldComponentUpdate
methods - Class component static
getDerivedStateFromProps
method - Function component bodies
- State updater functions (the first argument to
setState
) - Functions passed to
useState
,useMemo
, oruseReducer
By intentionally double-invoking methods like the component constructor, strict mode makes patterns like this easier to spot.
đź’ˇ The double invocation is the reason why we see double logs in the console when we do not expect them at all.
đź’ˇ Note:
Starting with React 17, React automatically modifies the console methods like console.log()
to silence the logs in the second call to lifecycle functions. (Not the function bodies
) However, it may cause undesired behavior in certain cases where a workaround can be used.
23