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

avatar

Borislav Hadzhiev

Last updated: Apr 19, 2022

banner

Photo from Unsplash

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> );

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> ); }

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.

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 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.

Conclusion #

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.

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.