useLocation() may be used only in the context of a Router component

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# useLocation() may be used only in the context of a Router component

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.

uselocation may be used only in context of router

Here is an example of wrapping your React app in a Router in your index.js file.

index.js
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> );
The code for this article is available on GitHub

Now you can use the useLocation hook in your App.js file.

App.js
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> ); }

using use location hook in app js file

The code for this article is available on GitHub

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.

The best place to wrap your React app with a 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.

# Solve the error when using Jest testing library

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.

App.test.js
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 code for this article is available on GitHub

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.