React Router and Hooks

Learn how to access the state of the router and perform navigation from inside Function components using Hooks.

Since React Router 5.1.0, React Router’s own Hooks are now available to us. It’s now possible to access Router information in function components without using the withRouter() HOC, provided that these components are not directly used as an argument for the <Route /> element prop component (<Route component={MyComponent} />).

As is the case with most Hooks, using React Router’s own Hooks is a straightforward experience. Four Hooks allow us to access the location object, the history instance, the Route parameter, or the match object. Conveniently, these Hooks are aptly called useLocation, useHistory, useParams, and useRouteMatch. To use these Hooks, the component intended for the Hooks implementation needs to be nested within a <Router> tree. However, it’s not necessary for the component to follow directly after the Router element or be placed on the uppermost layer. These Hooks can access the Router context and can thus be used anywhere in your application.



The useLocation() Hook

First, let’s take a closer look at the useLocation() Hook. We can import it via the react-router-dom package. Once installed, we can access location data by using the return value of the Hook:

Get hands-on with 1200+ tech skills courses.