I’m not sure about everyone else, but when I started churning out React apps (ha!) using
create-react-app, I didn’t pay much attention to why exactly my
index.js file looked like this:
<React.StrictMode>? I just assumed it was something necessary for a React app to function and went about my daily coding blissfully clueless as to the why of it all. I’ve since started trying to dive deeper into as many aspects of React as I can and thought I’d take a look at this
StrictMode thingy that I’ve taken for granted for such a long time.
So What is StrictMode exactly?
Strict Mode was introduced in version 16.3 of React to help highlight potential problems in React applications. It is NOT a component that renders any UI but it IS a component that can be wrapped around other components to enable checks and warnings on those descendants.
As I hinted at above, when you create a React app by using
StrictMode is added by default. And the default is to wrap the entire App component in
StrictMode. What I had not realized is that you do NOT need to wrap your entire app in
StrictMode tags; you can actually restrict
StrictMode to only certain components.
In the above example,
StrictMode checks will NOT be activated for the
Spinner components, but they WILL be activated for the
SomeOtherComponent components. Whatever warnings are activated, wherever they are in your application tree, will show up in the browser developer tools console when the app is run but will not impact your production build.
What does StrictMode help with?
Besides ensuring that your app follows best practices,
StrictMode can detect:
- If your app or libraries are using React APIs which are deprecated
- If there are any components with unsafe lifecycles
- If there are any unexpected side effects
StrictMode has proven to be useful when working with new code bases that have quite a bit of legacy code. It can also be very useful when troubleshooting particularly tricky bugs. You can wrap components lower in your application tree in
<React.StrictMode/> tags and work your way up to see when warnings are detected to isolate the problem code.
Future versions of
StrictMode will most likely see other warnings added, so the general consensus seems to be that it’s a good idea to use it.