Last updated: Apr 6, 2024
Reading time·2 min
The error "useLocation() may be used only in the context of a Router
component" occurs when we try to use the useLocation
hook outside of the
Router context in React Router.
To solve the error, use the useLocation
hook only within the Router
context.
Here is an example of wrapping your React app in a Router
in your index.js
file.
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // 👇️ Wrap App in Router root.render( <Router> <App /> </Router> );
Now you can use the useLocation
hook in your App.js
file.
import { useLocation, } from 'react-router-dom'; export default function App() { const location = useLocation(); const handleClick = () => { console.log(location); }; return ( <div> <button onClick={handleClick}>Log location</button> </div> ); }
The error occurs because the useLocation
hook makes use of the context that
the Router
component provides, so it has to be nested inside of a Router
.
Router
component is in your index.js
file because that's the entry point of your React application.Once your entire app is wrapped with a Router
component, you can use any of
the hooks from the React Router package anywhere in your components.
The solution if you got the error while using the Jest testing library is the
same, you have to wrap the component that uses the useLocation
hook in a
Router
.
import {render} from '@testing-library/react'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; // 👇️ Wrap component that uses useLocation in Router test('renders react component', async () => { render( <Router> <App /> </Router>, ); // Your tests... });
The error occurs because the component you are rendering in your test or one of
its children makes use of the useLocation
hook.
You have to wrap all components that use any of the React Router hooks in a
Router
component because they need access to the context provided by the
Router
.
I've also written an article on how to get the current URL and Route in React Router.