In React Router v5, navigate programmatically using history.push(path) or history.replace(path) from the useHistory() hook (or props.history in route-wrapped components). In React Router v6 (and v7), replace useHistory() with useNavigate() and call navigate(path) or navigate(path, { replace: true }), optionally passing route state via state in v6 or the second argument in v5.
1. Programmatic Navigation in React Router v5 (useHistory())
In React Router v5, call useHistory() inside a function component inside <Router> and invoke history.push() to add a history entry or history.replace() to swap the current entry without mutating any external state:
// Programmatic navigation in React Router v5 using useHistory()
import React from "react";
import { useHistory } from "react-router-dom";
function CheckoutRedirectButton({ orderId, replaceHistory = false }) {
const history = useHistory();
const handleNavigate = () => {
if (!history || typeof orderId !== "string" || orderId.trim() === "") {
return;
}
const targetRoute = {
pathname: `/orders/${encodeURIComponent(orderId)}`,
state: Object.freeze({ fromCheckout: true })
};
if (replaceHistory) {
history.replace(targetRoute);
} else {
history.push(targetRoute);
}
};
return (
<button type="button" onClick={handleNavigate}>
View Order
</button>
);
}
- Push vs. Replace:
history.push()appends to the browser history stack, whilehistory.replace()overwrites the current entry (useful after login or form redirects). - Route state object: Passing
statecarries transient navigation metadata without exposing it in query parameters.
2. Programmatic Navigation in React Router v6 (useNavigate())
In React Router v6, useHistory() was removed in favor of useNavigate(). Pass the destination path as the first argument to navigate(to, options) and set { replace: true } or { state } in the options object (or pass a numeric delta like navigate(-1) to go back):
// Programmatic navigation in React Router v6 using useNavigate()
import React from "react";
import { useNavigate } from "react-router-dom";
function OrderDetailsNavigator({ orderId, replaceHistory = false }) {
const navigate = useNavigate();
const goToOrder = () => {
if (typeof navigate !== "function" || typeof orderId !== "string" || orderId.trim() === "") {
return;
}
const safePath = `/orders/${encodeURIComponent(orderId)}`;
navigate(safePath, {
replace: Boolean(replaceHistory),
state: Object.freeze({ fromCheckout: true })
});
};
const goBackSafely = () => {
if (typeof navigate === "function") {
navigate(-1);
}
};
return (
<div>
<button type="button" onClick={goToOrder}>
Open Order
</button>
<button type="button" onClick={goBackSafely}>
Back
</button>
</div>
);
}
- Unified
navigate(to, options)API: Combines push, replace ({ replace: true }), and route state ({ state: ... }) into one hook call. - Relative & delta navigation: Supports relative paths (
"../settings") and history stack steps (navigate(-1)).
3. Common Traps to Avoid
Programmatic route navigation across React Router v5 and v6 frequently runs into a few pitfalls:
- Calling
useHistory()in React Router v6 oruseNavigate()in v5: Each hook belongs to its respective major version—mixing them throws a runtime import/undefined error. - Calling navigation hooks outside a Router provider: Both
useHistory()anduseNavigate()require the component to render inside a router context (<BrowserRouter>,<HashRouter>, or data router provider). - Navigating inside render instead of an event handler or
useEffect: Triggeringhistory.push()ornavigate()directly during render causes side-effect loops or React warnings—call it inside event handlers or controlled effects.
TL;DR: Use useHistory() with history.push() / history.replace() in React Router v5, and useNavigate() with navigate(path, { replace, state }) in React Router v6.
