Programmatically Navigate
What I love about React Router is its dedication to declarative, "React like" code. The whole goal of the redesign to React Router v3 to v4 was to align React Router's vision with React's. Fundamentally, what this means is that the same mental model that applies to React should also apply to React Router.
If you broke React down into three core principles, you'd get component composition, declarative UI, and state management - specifically, **user event -> state change -> re-render**
. Because React Router's vision is aligned with React's, programmatically navigating with React Router should, by definition, align with those three core concepts. The reason I'm emphasizing this is because your initial reaction to what's coming next will most likely be negative.
We are provided with a <Redirect />
component as a very declarative way of telling react-router to redirect us to another page. This follow’s react declarative way of doing things, however, it involves adding state and conditional logic after a re-render based on the state change.
There is a more imperative way of doing this, it’s faster and may be easier to read, but also less declarative so… tradeoffs!
That is using useHistory
custom hook, which allows us to use history methods like history.push()
or history.replace()
.
other