skip to Main Content

I have a React component that should only be displayed if the user are using the Electron browser. Hence, I want to have an early return in my React component so I don’t execute a lot of logic if the user is not using the Electron browser. I have the following minimal example:

export const MyComponent = () => {
    if (!isElectron) {
        return <p>You need to use Electron</p>
    }
    useEffect(() => {  // <-- gives error: React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render.
        console.log("You are using Electron");
    }, []);
    return <p>You are using Electron</p>
}

The useEffect in the example above gives the error: React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render. I simply want to ignore the error message for the whole file, and preferably not ignore other errors. How do I ignore the error message for a whole file?

2

Answers


  1. Chosen as BEST ANSWER

    If you have the chance, then the solution posted by @Giorgi Moniava is absolutely what you should be doing. If you are using Eslint and Visual Studio Code, then you can add the following line to the top of a file to ignore all rules-of-hooks errors:

    /* eslint-disable react-hooks/rules-of-hooks */.


  2. What you can do is move that condition in the parent component, where you are rendering that component:

    isElectron && <MyComponent/>
    

    The error says that you are breaking one of the rules of hooks. So you can’t do that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search