Design Converter
Education
Last updated on Mar 15, 2025
•5 mins read
Last updated on Mar 15, 2025
•5 mins read
Trying to manage navigation in a React app?
The useNavigate hook from react-router makes it easier to handle page changes and control the navigation flow. It's a handy tool for creating smooth transitions between pages based on user actions.
This article breaks down the core concepts of useNavigate, how it works with the history stack, and how to set up conditional navigation.
Let’s make React navigation simple!
The useNavigate hook, introduced in react-router, replaces the older useHistory hook, offering an improved way to navigate between routes programmatically. It allows developers to control navigation behavior inside functional components, avoiding the need for external dependencies.
• Controls the history stack, enabling forward and backward movement.
• Supports relative path navigation for flexible routing.
• Works with an optional object to customize navigation.
• Helps redirect users programmatically.
• Enhances view transition for better UX.
The useNavigate hook returns a function that allows developers to navigate to a different route path when called.
1import { useNavigate } from "react-router-dom"; 2 3const Home = () => { 4 const navigate = useNavigate(); 5 6 const goToAbout = () => { 7 navigate("/about"); 8 }; 9 10 return ( 11 <div> 12 <h1>Home Page</h1> 13 <button onClick={goToAbout}>Go to About</button> 14 </div> 15 ); 16}; 17 18export default Home;
The useNavigate hook is imported from react-router-dom.
navigate("/about")
updates the history stack, pushing a new entry.
Clicking the button redirects users to the target component.
Navigating using a relative path makes applications more maintainable.
1import { useNavigate } from "react-router-dom"; 2 3const Dashboard = () => { 4 const navigate = useNavigate(); 5 6 return ( 7 <div> 8 <h1>Dashboard</h1> 9 <button onClick={() => navigate("profile")}>Go to Profile</button> 10 </div> 11 ); 12}; 13 14export default Dashboard;
Here, navigate("profile")
navigates to /dashboard/profile
, following the route hierarchy.
Navigating through the browser history is essential for user interactions. The useNavigate function allows movement within the history stack.
1const BackButton = () => { 2 const navigate = useNavigate(); 3 4 return ( 5 <button onClick={() => navigate(-1)}>Go Back</button> 6 ); 7};
• navigate(-1) moves to the previous page.
• navigate(1) moves forward.
Sometimes, it's necessary to pass data when navigating. The second argument of navigate accepts an options object, allowing developers to send state.
1const Contact = () => { 2 const navigate = useNavigate(); 3 4 const sendMessage = () => { 5 navigate("/message", { state: { user: "John Doe" } }); 6 }; 7 8 return ( 9 <button onClick={sendMessage}>Send Message</button> 10 ); 11};
Inside the target component, retrieve the state:
1import { useLocation } from "react-router-dom"; 2 3const Message = () => { 4 const location = useLocation(); 5 const { user } = location.state || {}; 6 7 return <h2>Message for {user}</h2>; 8};
This method helps maintain the navigation flow without using a global state.
To prevent an entry in the history, use the replace option.
1navigate("/dashboard", { replace: true });
This replaces the current entry, preventing users from going back.
Conditional navigation ensures users navigate programmatically only when conditions are met.
1const ProtectedRoute = () => { 2 const navigate = useNavigate(); 3 const isAuthenticated = false; // Assume authentication check 4 5 if (!isAuthenticated) { 6 navigate("/login"); 7 } 8 9 return <h1>Protected Content</h1>; 10};
• The current URL is checked.
• If authentication fails, users are redirected.
Developers can configure specific styles or behaviors when navigating using an options object.
1navigate("/profile", { state: { userId: 42 } });
Splat routes allow handling unknown paths dynamically.
1<Route path="docs/*" element={<Docs />} />
Use useParams to get the splat:
1const { "*": subRoute } = useParams();
This captures everything after /docs/
.
A structured navigation logic ensures smooth transitions between pages.
This diagram represents a basic navigation flow using useNavigate.
After a form submission, users should be redirected to another page.
1const SubmitForm = () => { 2 const navigate = useNavigate(); 3 4 const handleSubmit = (e) => { 5 e.preventDefault(); 6 navigate("/thank-you"); 7 }; 8 9 return ( 10 <form onSubmit={handleSubmit}> 11 <button type="submit">Submit</button> 12 </form> 13 ); 14};
The navigate component allows redirection inside JSX.
1import { Navigate } from "react-router-dom"; 2 3const RedirectToHome = () => <Navigate to="/home" />;
Use this inside conditional rendering:
1{isLoggedIn ? <Dashboard /> : <Navigate to="/login" />}
To prevent users from leaving a page (e.g., unsaved changes), use the useEffect hook:
1useEffect(() => { 2 const handleBeforeUnload = (event) => { 3 event.preventDefault(); 4 event.returnValue = ""; 5 }; 6 7 window.addEventListener("beforeunload", handleBeforeUnload); 8 9 return () => { 10 window.removeEventListener("beforeunload", handleBeforeUnload); 11 }; 12}, []);
The useNavigate hook in react-router makes navigation smoother and more flexible. It supports relative paths, route hierarchy, and conditional navigation, giving developers more control over user flow.
By setting up basic navigation, passing data between routes, and using splat routes, developers can create smooth page transitions while keeping the history stack intact. With useNavigate, managing navigation in a React app becomes more straightforward and user-friendly.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.