Skip to content

Enforce consistent hook order for all hooks, including useContext #1384

Closed as not planned
@12joan

Description

@12joan

Describe the feature you'd like:

When calling the rerender method returned by renderHook, it would be useful for the library to throw an error like React does if the order of native React hooks called is not the same between renders.

In practice, this is already the case for some hooks like useMemo and useState whose implementation is dependent on order by necessity, but it is not the case for useContext, for example.

const MyContext = createContext(null);

let firstRender = true;
const useMyHook = () => {
  if (!firstRender) {
    useContext(MyContext);
  }
  firstRender = false;
};

// Expected: An error is thrown due to inconsistent hook order
// Actual: No error is thrown
renderHook(useMyHook).rerender();

Describe alternatives you've considered:

When writing idiomatic React code, this case should not arise. However, library code often needs to bend the rules, and having a test suite that ensures we're doing so safely would make it much easier to catch bugs.

Teachability, Documentation, Adoption, Migration Strategy:

In some niche circumstances where the use of hooks in test code differs from their use in production, this may be a breaking change for some users, especially if the implementation of the hook order check differs from React's implementation in some cases. For this reason, I would recommend adding an option to bypass the hook order check.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions