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]);
}
1
  • 1
    Looks like a good use case for a custom hook Commented Jan 23, 2021 at 16:29

1 Answer 1

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]);
Sign up to request clarification or add additional context in comments.

5 Comments

but does it strip it from the minified code though? Since it will never reach that path?
@ArchimedesTrajano, It will be part of the code, but will not execute until it matches the condition.
OK my Q is to make sure it is stripped off the minified output.
Take a look on this thread stackoverflow.com/questions/28572380/…
Is there a specific set of instructions on how to integrate that with a ReactJS build?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.