Programmatically navigate using React router

Mike Dodge
3 min readMar 17, 2021

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

import { useHistory } from "react-router-dom";function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}

React Router v4

With v4 of React Router, there are three approaches that you can take to programmatic routing within components.

  1. Use the withRouter higher-order component.
  2. Use composition and render a <Route>
  3. Use the context.

React Router is mostly a wrapper around the history library. history handles interaction with the browser's window.history for you with its browser and hash histories. It also provides a memory history which is useful for environments that don't have a global history. This is particularly useful in mobile app development (react-native) and unit testing with Node.

A history instance has two methods for navigating: push and replace. If you think of the history as an array of visited locations, push will add a new location to the array…

--

--

Mike Dodge

As Principal Design Technologist in Alexa Voice Shopping at Amazon, I design and build prototypes that define the future of voice and multi-model shopping.