Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
React-Router Hooks
Next article icon

React-Router Hooks

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Pre-requisite:

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

 Note: You need to have React >= 16.8 installed on your device, otherwise the hooks won't work.

What are React Router Hooks?

React Router hooks are the predefined functions used to interact with the router and manage navigation, locations, and url parameters in functional components. These hooks are provided by the React Router which is a routing and navigation library for React.

Table of Content

  • Hooks Of React Router 5:
  • useHistory Hook:
  • useParams Hook:
  • useLocation Hook:
  • useRouteMatch Hook :
  • Reason to use React Router Hooks

Hooks Of React Router 5:

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

  • useHistory
  • useParams
  • useLocation
  • useRouteMatch

React-Router is essential for navigation in React applications.

Now, We will discuss all the hooks in detail with proper examples:

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.

useParams Hook

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

Syntax: 

import { useParams } from "react-router-dom";
// Inside a functional component
export default function SomeComponent(props){
const params = useParams();
}

These URL parameters are defined in the Route URL. For example, 

<Route path="/profile/:userName" component={Profile} />

The colon(":") after "/profile/" specifies that "userName" is actually a variable or parameter that is dynamic. For example, in the url "/profile/johndoe", "johndoe" is the value of the parameter "userName". So, in this case, the object returned by useParams() is:

{
userName: "johndoe"
}

Example: After the login we want our user to be redirected to the "profile/userName" URL. The userName depends on the user's given name.  So, we need to set the URL path dynamically based on the user given userName. This is easy to do, we need to update the App.js file a little.

JavaScript
// Filename - App.js  import { Route, Switch } from "react-router-dom"; import Home from "./components/Home"; import ContactUs from "./components/ContactUs"; import LogIn from "./components/LogIn"; import AboutUs from "./components/AboutUs"; import Profile from "./components/Profile";  export default function App() {     return (         <div className="App">             <Switch>                 <Route path="/" exact>                     <Home someProps={{ id: 54545454 }} />                 </Route>                 <Route path="/about">                     <AboutUs />                 </Route>                 <Route path="/contact-us">                     <ContactUs />                 </Route>                 <Route path="/log-in">                     <LogIn />                 </Route>                 {/* userName is now a variable */}                 <Route path="/profile/:userName">                     <Profile />                 </Route>             </Switch>         </div>     ); } 
JavaScript
// Filename - Profile.js  import { useParams } from "react-router-dom";  export default function Profile(props) {     // useParams() returns an object of the parameters     // defined in the url of the page     // For example, the path given in the Route component     // consists of an "userName" parameter     // in this form ---> "/profile/:userName"     const { userName } = useParams();      return (         <div>             <h1> Profile of {userName}</h1>              <p> This is the profile page of {userName}</p>         </div>     ); } 

Output: Now if you now go to the log-in page and click the login button with userName "John", then you will be redirected to the "profile/john" page.

useLocation Hook

This hook returns the location object used by the react-router. This object represents the current URL and is immutable. Whenever the URL changes, the useLocation() hook returns a newly updated location object. Some of its use includes extracting the query parameters from the URL and doing something depending on the query parameters. The "search" property of the location object returns a string containing the query part of the URL.

Syntax :

import { useLocation } from "react-router-dom";
// Inside functional component
export default function SomeComponent(props){
const location = useLocation();
}

Note: history.location also represents the current location, but it is mutable, on the other hand, the location returned by useLocation() is immutable. So, if you want to use the location instance, it is recommended to use the useLocation() hook.

Example: The useLocation() is very useful to get and use the query parameters defined in the URL. In the below code we have used the useLocation hook to access the query parameters. Then we parsed it using the URLSearchParams constructor.

JavaScript
// Filename - Profile.js  import { useLocation } from "react-router-dom";  export default function Profile(props) {     const location = useLocation();      // location.search returns a string containing all     // the query parameters.     // Suppose the URL is "some-website.com/profile?id=12454812"     // then location.search contains "?id=12454812"     // Now you can use the URLSearchParams API so that you can     // extract the query params and their values     const searchParams = new URLSearchParams(         location.search     );      return (         <div>             {                 // Do something depending on the id value                 searchParams.get("id") // returns "12454812"             }         </div>     ); } 

Output :

Displays the given query id

useRouteMatch Hook

Returns a match object that contains all the information like how the current URL matched with the Route path. 

Properties:

  • params: This is an object that contains the variable part of the URL.
  • isExact: This is a boolean value, indicating whether the entire URL matched with the given Router path.
  • path: A string that contains the path pattern.
  • URL: A string that contains the matched portion of the URL. It can be used for nested <Link />s and <Route />s.

Syntax :

import { useRouteMatch } from "react-router-dom";
// Inside functional component
export default function SomeComponent(props) {
const match = useRouteMatch();
}

Example: The useRouterMatch hook can be used in creating nested Routes and Links. The following code renders the Profile page of the user when the current URL path entirely matches the given Route path, otherwise, it renders another Route that renders the User's followers page when the current URL path is  "profile/:userName/followers".

JavaScript
// Filename - Profile.js  import {     Link,     Route,     useParams,     useRouteMatch, } from "react-router-dom";  export default function Profile(props) {     // useParams() returns an object of the parameters     // defined in the url of the page     // For example, the path given in the Route component     // consists of an "userName" parameter     // in this form ---> "/profile/:userName"     const { userName } = useParams();     const match = useRouteMatch();      return (         <div>             {match.isExact ? (                 <div>                     <h1> Profile of {userName}</h1>                      <p>                         {" "}                         This is the profile page of{" "}                         {userName}                     </p>                      <Link to={`${match.url}/followers`}>                         Followers                     </Link>                 </div>             ) : (                 <Route path={`${match.url}/followers`}>                     <div>My followers</div>                 </Route>             )}         </div>     ); } 

Output:

If you click the follower's link, you will be redirected to the "/profile/John/followers" page, and as the entire URL path "profile/John/followers" does not match the given Route path i.e. "profile/;userName", so the div element inside the Route component gets rendered.

Remember You need to have React 16.8 or higher in order to use these react-router hooks. Also, don't forget to use them inside functional components.

Reason to use React Router Hooks

Before React Router 5:

By default, while using the component prop (<Route component={} />), React router passes three props(match, location, history) to the component that the Route renders. That means, if you, for some reason, want to access the history or location instance used by React router, you can access it through the default props.

But if you pass your custom props to your components then the default props get overridden by your custom props. As a result, you will not have any further access to the history object created by React Router. And before React Router 5, there was no way other than using the render prop (<Router render={} />) to explicitly pass the location, match, and history instance as props.

JavaScript
// Filename - App.js  import "./styles.css"; import { Route, Switch } from "react-router-dom"; import About from "./components/About";  export default function App() {     return (         <div className="App">             <Switch>                 // In this case, you have to use render //                 instead of component and explicitly // pass                 the props                 <Route                     path="/about"                     render={({                         match,                         location,                         history,                     }) => (                         <About                             match={match}                             location={location}                             history={history}                             someProps={{ id: 21254 }}                         />                     )}                 />             </Switch>         </div>     ); } 
JavaScript
// Filename - About.js  import { useLocation } from "react-router-dom";  export default function (props) {     // Accessing the location and history     // through the props     const location = props.location;     const history = props.history;     return <div>// Some content</div>; } 

With React Router 5 Hooks:

Now with React Router 5, you can easily pass your custom props to the rendering component.

Though in this case also those three props (match, location, history) don't get past the rendered components automatically, we can now use the hooks provided by React Router 5, and we don't need to think about the props anymore. You can directly access the history object by using the useHistory hook, location object with useLocation hook, and match the object with useRouteMatch hook, and you don't have to explicitly pass the props to the components.  

JavaScript
// Filename - App.js  import "./styles.css"; import { Route, Switch } from "react-router-dom"; import Home from "./components/Home"; import ContactUs from "./components/ContactUs"; import LogIn from "./components/LogIn"; import AboutUs from "./components/AboutUs";  export default function App() {     return (         <div className="App">             <Switch>                 <Route path="/" exact>                     <Home someProps={{ id: 54545454 }} />                 </Route>                 <Route path="/about">                     <AboutUs />                 </Route>                 <Route path="/contact-us">                     <ContactUs />                 </Route>                 <Route path="/log-in">                     <LogIn />                 </Route>             </Switch>         </div>     ); } 
JavaScript
// Filename - Home.js  import {     useHistory,     useLocation,     useParams,     useRouteMatch, } from "react-router-dom";  export default function Home(props) {     // Access the history object with useHistory()     const history = useHistory();      // Access the location object with useLocation     const location = useLocation();      // Access the match object with useRouteMatch     const match = useRouteMatch();      // Extract the URL parameters with useParams     const params = useParams();      return <div>{/* Some code */}</div>; } 



Next Article
React-Router Hooks

R

riter79
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

    React Router
    React Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes, providing a seamless user experience by mapping various URLs to components. It enables navigation in a single-page application (SPA) without refreshing the entire page.This
    6 min read
    React Hooks Tutorial
    React Hooks were introduced to solve some problems with class components in React. With Hooks, you can now add state, lifecycle methods, and other React features to functional components, which previously only class components could do. This makes development simpler because you can handle stateful
    3 min read
    React Hooks
    ReactJS Hooks are one of the most powerful features of React, introduced in version 16.8. They allow developers to use state and other React features without writing a class component. Hooks simplify the code, make it more readable, and offer a more functional approach to React development. With hoo
    10 min read
    NPM React Router Dom
    React Router DOM is a powerful routing library for React applications that enables navigation and URL routing. In this article, we'll explore React Router DOM in-depth, covering its installation, basic usage, advanced features, and best practices. What is React Router DOM?React Router DOM is a colle
    2 min read
    What is React Router?
    React Router is like a traffic controller for your React application. Just like how a traffic controller directs vehicles on roads, React Router directs users to different parts of your app based on the URL they visit. So, when you click on a link or type a URL in your browser, React Router decides
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences