Open In App

How to use the useHistory hook in React Router?

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 react-router-dom@5.3.0

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.

useHistory hook in React Router:

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 react-router-dom@5.3.0

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:

Recording2024-03-18215115-ezgifcom-video-to-gif-converter

Output for useNavigate

There 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.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads