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