Is it possible to detect whether the current version of React is development or production at runtime? I'd like to do something like this:
if (React.isDevelopment) { // Development thing } else { // Real thing }
To identify which environment we are in, we can make use of a special environment variable: process. env. NODE_ENV . When you are using Create React App, the react-scripts will set the value of NODE_ENV to development when npm start is executed and to production when you run npm run build .
To optimize React rendering, you need to make sure that components receive only necessary props. It will let you control the CPU consumption and avoid over-rendering unnecessary features. The solution is to create a functional component that will collect all props and redistribute them to other components.
This is best done emulating the Node way of doing things with your build tool - webpack, browserify - by exposing process.env.NODE_ENV
. Typically, you'll have it set to "production" in prod and "development" (or undefined) in dev.
So your code becomes:
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') { // dev code } else { // production code }
For how to set it up, see envify or Passing environment-dependent variables in webpack
I use a helper file (in Typescript):
import process from "process"; const development: boolean = !process.env.NODE_ENV || process.env.NODE_ENV === 'development'; export default function isDev(): boolean { return development; }
Then elsewhere I use it like this:
import isDev from "./helpers/DevDetect"; if (isDev()) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With