Design Converter
Education
Last updated on Feb 14, 2025
•4 mins read
Last updated on Feb 14, 2025
•4 mins read
Want to make navigation in your React app smoother?
The useHistory hook in React Router helps you handle navigation easily. It allows you to programmatically move between routes and track history changes. This guide will show you how to use the useHistory hook with React Router DOM, explain how the history object works, and teach you how to push new entries onto the history stack.
By the end, you’ll know how to handle navigation in functional components and integrate it into your React projects.
Let’s get started!
The useHistory hook is part of React Router DOM and allows functional components to access the history object, making it easy to programmatically navigate between different routes. Unlike traditional navigation through anchor tags (<a>
), useHistory gives developers complete control over the navigation process, enabling smooth transitions in single page applications.
The history object is a key component of React Router DOM, and it represents the browser's session history stack. Each navigation action (like clicking a link or using push) creates a new entry in the history stack.
• Programmatic navigation with push and replace
• Accessing and manipulating the current entry in the history stack
• Tracking the current location and handling the URL hash fragment state
• Passing location-specific state between different components
To start using the useHistory hook, you need to import it from React Router DOM:
1import { useHistory } from 'react-router-dom';
Once imported, you can call useHistory() in a functional component to get access to the history object.
1import React from 'react'; 2import { useHistory } from 'react-router-dom'; 3 4const LoginComponent = () => { 5 const history = useHistory(); 6 7 const handleLogin = () => { 8 // Simulate a login process and navigate to the dashboard 9 history.push('/dashboard', { from: 'login' }); // push path state 10 }; 11 12 return ( 13 <div> 14 <h1>Login</h1> 15 <button onClick={handleLogin}>Go to Dashboard</button> 16 </div> 17 ); 18}; 19 20export default LoginComponent;
In this LoginComponent, the handleLogin function uses the push method to navigate to the /dashboard
route and pass state ({ from: 'login' }
). This adds a new entry onto the history stack.
The history object returned by the useHistory hook has several useful methods and properties for managing navigation:
• push(path, state)
: Pushes a new entry onto the history stack with an optional state.
• replace(path, state)
: Replaces the current entry in the history stack with the specified path and state.
• goBack()
: Moves to the previous entry in the history stack.
• goForward()
: Moves to the next entry in the history stack.
1const Profile = () => { 2 const history = useHistory(); 3 4 const goToSettings = () => { 5 history.push('/settings'); // pushes a new entry onto the history stack 6 }; 7 8 const replaceWithHome = () => { 9 history.replace('/'); // replaces the current entry 10 }; 11 12 return ( 13 <div> 14 <h2>Profile Page</h2> 15 <button onClick={goToSettings}>Go to Settings</button> 16 <button onClick={replaceWithHome}>Replace with Home</button> 17 </div> 18 ); 19};
In this example, goToSettings adds a new entry to the history stack, while replaceWithHome replaces the current entry.
The location object in React Router provides information about the current location, including the pathname, search, and hash. This is particularly useful for accessing url parameters.
1import { useLocation } from 'react-router-dom'; 2 3const CurrentLocation = () => { 4 const location = useLocation(); 5 6 return ( 7 <div> 8 <h2>Current URL: {location.pathname}</h2> 9 </div> 10 ); 11};
Here, useLocation returns the location object, which contains the current URL details.
In large React applications, it's common to pass state between different components and manipulate the history stack. The useHistory hook is an invaluable tool for building user interfaces that require dynamic routing.
For specific use cases, you might need memory history, especially in environments without a browser (like in tests or React Native). While the history stack behaves similarly, memory history doesn't rely on the browser's session history.
Avoid hardcoding URLs: Use route constants to ensure consistency.
Leverage state: Use the state parameter in push to pass data between routes.
Clean up listeners: When using history listeners, always remove them when they are no longer needed.
The useHistory hook in React Router DOM is a great way to manage navigation in your single page applications. By integrating it into your project, you can improve routing and create a smooth user experience. Start using the useHistory hook today and see how it can help you streamline your web development workflow.
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.