React Router hooks allow components to navigate between routes, read URL details, and work with dynamic parameters in a clean and declarative way.
Click the buttons to see how the simulated hooks update instantly.
These hooks are provided by react-router-dom and can only be used inside functional components wrapped by a Router.
// Programmatic navigation using useNavigate
import React from "react";
import { useNavigate } from "react-router-dom";
function NavigateExample() {
const navigate = useNavigate();
const handleClick = () => {
navigate("/about");
};
return (
<div>
<button onClick={handleClick}>Go to About</button>
</div>
);
}
export default NavigateExample;
// Navigate backward and forward in history
navigate(-1);
navigate(1);
// Accessing current URL information
import React from "react";
import { useLocation } from "react-router-dom";
function LocationExample() {
const location = useLocation();
return (
<div>
<p>Path: {location.pathname}</p>
<p>Query: {location.search}</p>
<p>State: {JSON.stringify(location.state)}</p>
</div>
);
}
export default LocationExample;
// Reading dynamic route parameters
import React from "react";
import { useParams } from "react-router-dom";
function UserPage() {
const { id } = useParams();
return (
<div>
<p>User ID: {id}</p>
</div>
);
}
export default UserPage;
// Defining routes with dynamic parameters
import React from "react";
import { Routes, Route } from "react-router-dom";
import UserPage from "./UserPage";
function App() {
return (
<Routes>
<Route path="/user/:id" element={<UserPage />} />
</Routes>
);
}
export default App;
Visiting /user/42 will display the value 42 dynamically inside the UserPage component.
useNavigate for redirects after login or submitlocation.state/product/:id