Skip to content

"{hook} may be used only in the context of a <Router> component" when running with vitest, node >=22.12 and there's a peer-dep on react-router #12785

Open
@acelaya

Description

@acelaya

I'm using React Router as a...

library

Reproduction

I created the minimum steps to reproduce in this repository: https://github.com/acelaya/peer-react-router-vitest

The readme includes the steps to reproduce the issue.

System Info

System:
    OS: Linux 6.8 Ubuntu 24.04.1 LTS 24.04.1 LTS (Noble Numbat)
    CPU: (16) x64 11th Gen Intel(R) Core(TM) i7-11700K @ 3.60GHz
    Memory: 50.17 GB / 62.68 GB
    Container: Yes
    Shell: 5.9 - /usr/bin/zsh
  Binaries:
    Node: 22.13.0 - ~/.nvm/versions/node/v22.13.0/bin/node
    npm: 10.9.2 - ~/.nvm/versions/node/v22.13.0/bin/npm
  Browsers:
    Chrome: 131.0.6778.264
  npmPackages:
    react-router: ^7.1.3 => 7.1.3 
    vite: ^6.0.5 => 6.0.8

Used Package Manager

npm

Expected Behavior

It should be possible to depend on packages that have a peer dependency on react-router, and have no errors when running with vitest.

Actual Behavior

In short, if your project depends on react-router and a dependency which in turn has a peer-dependency on react router, when running with vitests, all imports from react-router inside that dependency will resolve a different instance than the ones in the root project, causing errors like useLocation() may be used only in the context of a <Router> component.

This issue was reported in #12475, but it was then closed as a solution was provided that solved it for other use cases, but the error still exists when running with vitest.

It also only affects node 22.12 and newer. Earlier versions work as expected. This can be seen in this GitHub workflow execution, from the repro repository above: https://github.com/acelaya/peer-react-router-vitest/actions/runs/12864662838

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions