How to use the useHistory hook in React Router?
Last Updated :
20 Mar, 2024
React Router is a standard library system built on top of React and used to create routing in the React application using the React Router Package. It enables the navigation between views of various components in a React Application. React Router is useful for Single Page Applications (SPAs).
To use usHistory Hook in React Router, you first need to install an older version of React Router as it is deprecated.
You can do this with the following command:
npm installĀ [email protected]
Why do we need a React Router?
React Router is important because it allows users to display multiple views in a single-page application. For example, social media websites like Facebook and Instagram use React Router to render multiple views. React Router also provides a declarative way of managing routes in React applications, thereby reducing the stress that comes from manually setting routes for all of the pages and screens in your React application.
React Router enables users to:
- Navigate between components in a React application.
- Change the browser URL.
- Keep the UI in sync with the URL.
- Define multiple routes in the application.
- Provide navigation for react applications with multiple views.
- Provide a router to manage the URLs.
- Provide sub-packages specifically designed for mobile applications.
The useHistory hook is a React Router hook that allows you to access the history object. The history object contains information about the current URL, as well as the previous and next URLs in the history stack. You can use the useHistory hook to navigate to different routes in your application, as well as to go back and forth in the history stack.
Follow the Steps below to use the useHistory hook in your project.
1. Install the required packages in your project using the following command.
npm installĀ [email protected]
2. To use the useHistory hook, you first need to import it from the react-router-dom package:
import { useHistory } from 'react-router-dom';
3. Once you have imported the useHistory hook, you can use it in any functional component in your application. To do this, you simply need to call the useHistory hook and assign the result to a variable:
const history = useHistory();
4. The history variable will now contain a reference to the history object. You can use this variable to call any of the methods on the history object.
Example: Below is an example of useHistory hook in React Router.
Node
// App.js
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const history = useHistory();
const handleLogin = () => {
setIsLoggedIn(true);
// Navigate to the dashboard page programmatically
history.push('/dashboard');
};
const handleLogout = () => {
setIsLoggedIn(false);
// Navigate to the login page programmatically
history.push('/login');
};
const goBack = () => {
// Navigate back one step in history
history.goBack();
};
return (
<div>
{isLoggedIn ? (
<button onClick={handleLogout}>Logout</button>
) : (
<button onClick={handleLogin}>Login</button>
)}
<button onClick={goBack}
disabled={history.length <= 1}>
Go Back
</button>
</div>
);
}
export default App;
Output:
Output for useNavigateThere are many other usecases of useNavigate hook.
navigate(N)
| history.go(N)
| Description
|
---|
navigate (1)
| history.goForward()
| Navigates one page forward in the browser history.
|
---|
navigate(-1)
| history.goBack()
| Navigates one page backward in the browser history.
|
---|
Conclusion
The useHistory hook is a React Router hook that allows you to access the history object. The history object contains information about the current URL, as well as the previous and next URLs in the history stack. You can use the useHistory hook to navigate to different routes in your application, as well as to go back and forth in the history stack.
The useHistory hook is a powerful tool that can be used to create more dynamic and user-friendly React applications. By understanding how to use the useHistory hook, you can create applications that allow users to navigate between different views with ease. You can also use the useHistory hook to implement features such as back buttons and forward buttons.
Similar Reads
useRoutes Hook in React Router
React Router is a library that is used for handling navigation and routing in React applications. It provides a way to navigate between different components or pages while maintaining a single-page application (SPA) structure. One of the key features is the useRoutes hook. It allows you to define ro
4 min read
Replacement of useHistory hook in React
In this article, we will learn how to replace the useHistory hook in React. With the introduction of new versions of React Hooks, useNavigate in React replaced the useHistory hook. useNavigate hook is a React hook that allows you to navigate your application imperatively. Table of Content What is us
3 min read
How to Use useState() Hook in NextJS ?
In this article, we will learn How to use useState() hook provided by the 'react' library in the NextJS project.useState() HookThe React JS library includes the useState() hook. It is very useful in order to manage the state in our Next Js application. It allows us to add the state, and update the s
3 min read
What's the role of the useContext hook in React Hooks?
The useContext hook in React Hooks allows you to consume values from the React context without needing to explicitly pass props through every level of your component tree. Role of useContext hook in React Hooks:Accessing Context Values:With useContext, you can access values stored in a React context
2 min read
useLoaderData Hook in React Router
useLoaderData is a hook provided by React Router. React Router is a JavaScript framework that helps to create and handle routing in React applications. This hook helps to fetch the data for the component before it renders, this improves performance and prevents empty states. Data FetchingWithout the
3 min read
What are the React Router hooks in React v5?
React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information abou
5 min read
How to handle Nested Routes in React Router ?
React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in
3 min read
How to setup React Router v6 ?
React Router is an amazing library that was created by Remix. The purpose of React Router is to enable Client-Side routing in the React application, that is, by using React Router we can create different routes in our React app and can easily navigate to different pages without even reloading the pa
6 min read
Provide an example of using the useParams hook in React Router.
React Router is a popular library for routing in React applications. One of its powerful features is the useParams hook, which allows developers to access parameters from the URL in functional components. In this article, we'll explore the useParams hook in React Router with a practical example. Pre
3 min read
How to setup 404 page in React Routing?
When you're building a React app with routing, it's important to handle cases where users land on a page that doesn't exist. A 404 page is a good way to inform users that the page theyâre looking for cannot be found. Prerequisites:NPM & Node JSReact JSReact-router-domApproach to Set Up a 404 Pag
4 min read