sajad torkamani

React’s Strict Mode is a development tool that aims to help you catch potential problems with your React components. You enable it by wrapping your components in the <StrictMode /> component like so:

import React from 'react';

function ExampleApplication() {
  return (
    <div>
      <Header />
      <React.StrictMode>
        <div>
          <ComponentOne />
          <ComponentTwo />
        </div>
      </React.StrictMode>
      <Footer />
    </div>
  )
}

StrictMode will only operate during development.

How does it help

  • Warns if you use unsafe lifecycle methods.
  • Warns if you use deprecated APIs (e.g., findDOMNode()).
  • Detects impure component renders. In Strict Mode, React calls each component’s function twice. If the output is different given the same input, React warns you,

Caveat: Strict mode makes your app behave a little different in development

To detect unexpected side-effects in methods that should have no side effects or that should be deterministic (e.g., constructor or render), Strict Mode will invoke the following functions twice during development:

  • Class component constructorrender, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useStateuseMemo, or useReducer

In React 17, console.log is monkey patched so that it doesn’t output anything to the logs in the second invocation.

From React 18 on, logs aren’t suppressed but if you have the React DevTools extension, the logs from the second call will appear slightly dimmed like so:

React Strict Mode alters console.log

You can configure the extension to suppress the logs completely in the second invocation.

Tagged: React