How to force a order for calling React.js hooks

Viewed 576

Is it possible to enforce a specific order in which React hooks are used? For example some linting/prettier settings that will always make sure to first use 'useState' hooks and only after that use 'useEffect' hooks. Let's say I have the following code:

const MyComponent = () => {
    const [myState1, setMyState1] = React.useState();
    const [myState2, setMyState2] = React.useState();

    React.useEffect(() => {
        runSomeEffect()
    }, [])

    const [myState3, setMyState3] = React.useState();

    return <div>...</div>
}

I would like to have some sort of warning that the third useState hooks should be moved to the top. I looked into Eslint and Prettier, but I don't think any of those have rules to enforce the order of React hooks.

1 Answers

You can't have such rule as the call order of hooks matters due to Rules of Hooks.

By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

You have an in-depth explanation of why, here.

React relies on the order in which Hooks are called

Therefore such a rule may cause unexpected behavior where the developer would enforce order and the rule will break it.

Related