Is there a way to check if React's `StrictMode` is on?

5.8k Views Asked by At

Is there a way in React -- either in code or via the React devtools -- to see if a component is being rendered in React's StrictMode? In my dream world, there would be some kind of constant I could console.log, say a bool of React.isStrictModeOnForThisComponentRendering; or maybe when you inspect a component in the React devtools, it would say somewhere in the side panel if it's rendering in StrictMode or not.

To be clear, this question is:

  • Not about how do you enable StrictMode. (The answer is <React.StrictMode>, although it can also be set via configs in some frameworks, e.g., Next.js)
  • Specifically discussing React's StrictMode, not JavaScript's ('use strict';) or TypeScript's strict mode. It's an overloaded phrase, but watcha gonna do?
  • Motivated by the confusion you get due to unexpected double rendering with React's StrictMode. See this GitHub issue or this StackOverflow post for a sense of the frustration it can cause. It would be nice to have an easy way to verify a component is running in StrictMode even if you can't tell where in the component tree StrictMode has been enabled.
1

There are 1 best solutions below

0
On

It's not a clear or definitive way, but you can purposefully trigger a warning that is supposed to only occur in React's StrictMode. For example:

  • You could purposefully create a dummy component that makes use of an unsafe lifecycle, and it should trigger a warning. This is a bit of a hassle since -- if you're using only functional components throughout your app -- you must create a class component to make use of the unsafe lifecycle methods.
  • You could purposefully use a (deprecated) string ref in a component, and it should trigger a warning. This is easier but uglier than the above with functional components: you can put it in any component's JSX, but it will cause your app to just completely break if it's a functional component. But the warning should at least still appear before the app breaks. CAVEAT: I just tried reproducing this and while I'm still confident my app is in React StrictMode, I can no longer get the string ref to trigger the warning as I had been seeing it before, it's only breaking the app. Not sure what has changed or I'm doing differently, but this might not be as good a check as the above option.

In any case, this warning will contain some text like this

... found within a strict-mode tree ...

which seems like reasonably good proof that the component is rendering in StrictMode. Would be nice to have a more direct helper function, but it works in a pinch.