Every year, Santa Claus and his helping elves create a special list for every child in the world: the Naughty or Nice list. React has something quite similar – Strict Mode.
3 min read
By Markus Rauhut
December 1, 2019
Strict Mode is a feature already introduced to React 16.3 in March 2018. Still, chances are you've never used it before. Strict Mode does not render anything visual (similar to
Fragment), but detects potential problems in your code and gives you helpful warnings. Strict Mode runs in development mode only and doesn't affect your production build. With the introduction of Hooks earlier this year and Concurrent Mode just around the corner, Strict Mode is becoming an increasingly important tool for locating bad practices (Concurrent mode probably won't work until you have fixed the warnings thrown in Strict Mode).
Like everything else that is made of code, React changes over time and what was once considered state of the art eventually becomes deprecated and replaced. Such as
findDOMNode which is deprecated in Strict Mode and possibly will be removed in a future version of React. Other examples are the use of string refs and the legacy context API, both of which cause some issues.
Since release 16.9, React throws a warning when using any of the lifecycle methods
componentWillUpdate. You've hopefully converted these methods into safer alternatives by now (if not, you should at least add an "UNSAFE_" prefix). Strict Mode can help you identify unsafe lifecycle methods in your own code and third-party libraries, and also suggests alternative methods.
In Concurrent Mode, React may trigger the
render method multiple times before actually committing the changes (e.g. changing the DOM). Therefore, it is important that this method doesn't contain side effects which can lead to memory leaks and invalid state. Strict Mode can't detect these side effects automatically, but uses a simple yet clever trick to make them easier to spot – the methods
getDerivedStateFromProps all get double invoked. If this leads to any weird behaviour in your app, you know what to look for.
Fortunately, using Strict Mode is amazingly easy – all you have to do is to wrap whatever you want to use Strict Mode on inside
<React.StrictMode />. This can be your entire
<React.StrictMode> <App> <Component1 /> <Component2 /> </App> </React.StrictMode>
Or just a single component:
<App> <React.StrictMode> <Component1 /> </React.StrictMode> <Component2 /> </App>
This way, you can gradually apply Strict Mode to your app without having to correct everything at once.
If you want to see Strict Mode in action, you should check out this CodeSandbox created by Kent C. Dodds' (warnings can be found in the console output):