3

In my React functional component, I use useEffect to do some debug logging, but I only want it when I am running in a non --production build.

// something like
if (process.env.NODE_ENV !== 'production') {
  // I want the contents of this block removed on production builds, but it is inside a function
  useEffect(() => {
    console.log("authState changed", AuthStates[authState]);
  }, [authState]);

  useEffect(() => {
    console.log("authToken changed", authToken);
    if (tokenExpiresOn) {
      console.log(
        `token expires in ${(tokenExpiresOn - Date.now()).toLocaleString()}ms`
      );
    }
  }, [authToken]);

  useEffect(() => {
    if (tokenExpiresOn) {
      console.log(
        `token expires in ${(tokenExpiresOn - Date.now()).toLocaleString()}ms`
      );
    } else {
      console.log("tokenExpiresOn cleared");
    }
  }, [tokenExpiresOn]);
}
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

1 Answers1

1

You can not declare hooks conditionally. You can declare on the top level and you can put your business logic inside the hook, e.g below.

useEffect(() => {
   if (process.env.NODE_ENV !== 'production'){
    console.log("authToken changed", authToken);
    if (tokenExpiresOn) {
      console.log(
        `token expires in ${(tokenExpiresOn - Date.now()).toLocaleString()}ms`
      );
    }
 }
  }, [authToken]);
Sam
  • 1,040
  • 1
  • 7
  • 11