Home > Enterprise >  ReactJS to have code only available in dev envrionment
ReactJS to have code only available in dev envrionment

Time:02-01

I have a ContextProvider that does things a little different in production than in development. The background is that the app is supposed to get embedded in a CMS and the form is provided by the CMS. However I develop it standalone because the CMS is also still in development by someone else, therefore I created my own form and API.

I have in dev environment two useEffect hooks that take in data from my mockup API

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {

  useEffect(()=>{
    setWidth(parseInt(props.width));
  }, [props.width]);
  //...
}

props.width (as an example) gets assigned to the ContextProvider-component only in development, it's not supposed to be available in production.

However I can not have useEffect in a condition. How would I prevent development-functionality being compiled in the production build? Is it good practice to have the whole ContextProvider in a condition one version with the development functionality and in the else branch again but without development functionality? This would however mean I have some code twice...

PS: Please note that I did not want to have the useEffect appear in production. So having the condition inside the useEffect is not a solution, this way I would have an useEffect in production that is never getting used as props.width doesn't even exist in this case.

CodePudding user response:

Hooks cannot be called conditionally, so just move condition inside useEffect:

useEffect(() => {
  if (!process.env.NODE_ENV || process.env.NODE_ENV === "development") {
    setWidth(parseInt(props.width));
  }
}, [props.width]);

CodePudding user response:

React rules say: Don’t call Hooks inside loops, conditions, or nested functions.

But this is not exactly true. The real rule is:

The amount of hook calls should be same inside the component on each render after the component mount.

So, if you ensure that the condition you use is always false or always true after the component mount, you can put the hooks inside condition.

checking process.env.NODE_ENV === "development"is always true or always false after you start your app, you can not change it during runtime via .env (you have to restart the app in order for the changes to be applied) and this is a valid condition.

You have to disable eslint rule of hooks for that use

  • Related