useHistory Hook

This is one of the most popular hooks provided by React Router. It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page. The history instance created by React Router uses a Stack( called “History Stack” ), that stores all the entries the user has visited.

Syntax :

import { useHistory } from "react-router-dom";

// Inside a functional component
export default function SomeComponent(props){
// The useHistory() hook returns the history
// object used by React Router
const history = useHistory();
}

The history object returned by useHistory() has various properties and methods.

Properties: 

  • length: Returns a Number. The number of entries in the history stack
  • action: Returns a string representing the current action (PUSH, REPLACE, or POP).
  • location: Returns an object that represents the current location. It may have the following properties:
    • pathname: A string containing the path of the URL
    • search: A string containing the URL query string
    • hash: A string containing the URL hash fragment
    • state: An object containing location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.

Methods:

  • push(path, [state]): Pushes a new entry onto the history stack. Useful to redirect users to page
  • replace(path, [state]): Replaces the current entry on the history stack
  • go(n): Moves the pointer in the history stack by n entries
  • goBack(): Equivalent to go(-1).
  • goForward(): Equivalent to go(1).
  • block(prompt): Blocks navigation. It takes a callback as a parameter and invokes it after the navigation is blocked. Most useful when you want to first confirm if the user actually wants to leave the page.

Example: Suppose we have a React project created using “create-react-app” having the following project structure.

Project structure:

react-router-hooks-tutorial/
|--public/
|--src/
| |--components/
| | |-->Home.js
| | |-->ContactUs.js
| | |-->AboutUs.js
| | |-->LogIn.js
| | |-->Profile.js
| |-->App.js
| |-->App.css
| |-->index.js
| |-->index.css
| |-->... (other files)
|-- ...(other files)

Suppose, inside the “LogIn.js”, we have a “LogIn” component that renders the log-in page. The LogIn component renders two input fields, one for the username and another for a password. When the user clicks the login button, we want to authenticate the user and redirect the user to his/her profile page.

Javascript




// Filename - LogIn.js
 
import { useHistory } from "react-router-dom";
import { useState } from "react";
 
// A function that authenticates the users
function authenticateUser(userName, password) {
    // Some code to authenticate the user
}
 
// Hooks must be used inside a functional component
export default function Login(props) {
    //Creating a state variable
    const [userName, setUserName] = useState("");
    const [password, setPassword] = useState("");
 
    // Accessing the history instance created by React
    const history = useHistory();
 
    // Handle the user clicks the login button
    const handleClick = () => {
        // Authenticate the user
        authenticateUser(userName, password);
 
        // When the authentication is done
        // Redirect the user to the `/profile/${userName}` page
        // the below code adds the `/profile/${userName}` page
        // to the history stack.
        history.push(`/profile/${userName}`);
    };
 
    return (
        <div>
            <input
                type="text"
                value={userName}
                onChange={(e) => {
                    setUserName(e.target.value);
                }}
                required
            />
            <input
                type="text"
                value={password}
                onChange={(e) => {
                    setPassword(e.target.value);
                }}
                required
            />
            <button type="submit" onClick={handleClick}>
                {" "}
                Log In{" "}
            </button>
        </div>
    );
}


Output:

Log in page

Check the Login component carefully, the “handleClick” function takes the username and password and calls the “authenticateUser” function which somehow authenticates the user. When the authentication is done, we want to redirect the user to the “profile/John” (suppose the username is “John”) page. That’s what the last line of handleClick function does. “useHistory()” hook returns the history instance created by React Router, and history.push(“/profile/John”) adds the given URL to the history stack which results in redirecting the user to the given URL path. Similarly, you can use other methods and parameters of the history object as per your need.

Check the next hook to see how the redirection to a dynamic URL works.

React-Router Hooks

React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single page.

Similar Reads

Pre-requisite:

NPM & Node JS React JS React JS Router React JS Types of Routers...

Hooks Of React Router 5:

These are 4 React Router Hooks in v 5 that you can use in your React applications:...

useHistory Hook:

This is one of the most popular hooks provided by React Router. It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page. The history instance created by React Router uses a Stack( called “History Stack” ), that stores all the entries the user has visited....

useParams Hook:

...

useLocation Hook:

This hook returns an object that consists of all the parameters in URL....

useRouteMatch Hook :

...

Reason to use React Router Hooks

...

Contact Us