Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 vs. React Router DOM
Next article icon

What are the React Router hooks in React v5?

Last Updated : 03 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 about the desired URL and navigating through web pages.

We will discuss the different React Router hooks in React v5:

Table of Content

  • useParams
  • useLocation
  • useHistory
  • useRouteMatch

Prerequisites:

  • ReactJS
  • ReactJS Hooks
  • ReactJS Router

useParams

useParams hook is a functional component hook that is used to extract dynamic route parameters from the current or active URL. The term Params in 'useParams' defines parameters that are used to retrieve data from a URL. useParams retrieves an object containing key-value pairs where the keys are parameter names defined in the route path and the values are corresponding parameter values from that URL.

It's important to define the expected parameters in the route path using colons (:). If a parameter is not present in the URL its respective value in the object will be "undefined".

Example: Below is an example of useParams. In the below code the useParams() retrieves the parameters or values of the URL and destructures them as "productId" and "color". Parameters of URL are '123' and 'blue'.

JavaScript
import {     BrowserRouter,     Routes,     Route } from 'react-router-dom'; import MyComponent from './MyComponent';  function App() {     return (         <BrowserRouter>             <Routes>                 <Route path="/products/:productId/:color"                     element={<MyComponent />} />             </Routes>         </BrowserRouter>     ); }  function MyComponent() {     const { productId, color } = useParams();      return (         <div>             <p>Product ID: {productId}</p>             <p>Color: {color}</p>         </div>     ); }  export default App; 

Output :

output-1


useLocation

useLocation retrieves the current URL information as an object, this object changes whenever the user navigates to a new URL. Object provides properties like pathname, search string and a hash fragment. useLocation hook can also be used in cases like triggering events by a change in URL.

useLocation only reflects the current URL and doesn't triggger re-renders when the URL changes on its own. If you need to respond to your URL changes , consider using the "useEffect" hook along with the "useLocation" hook.

Example: Below is an example of useLocation. In the below code the "location.search() " returns the entire string after " ? " from the URL.

JavaScript
import {     BrowserRouter,     Routes,     Route } from 'react-router-dom'; import MyComponent from './MyComponent';  function App() {     return (         <BrowserRouter>             <Routes>                 <Route path="/" element={<MyComponent />} />                 <Route path="/products/:productId"                     element={<MyComponent />} />             </Routes>         </BrowserRouter>     ); }  function MyComponent() {     const location = useLocation();      return (         <div>             <p>Current Path: {location.pathname}</p>             <p>Search String: {location.search}</p>         </div>     ); } export default App; 

Output:

output-2

useHistory

useHistory hook provides access to history object that manages the history stack. History stack contains all the URL's visited by the user. "useHistory" hook grants access to history instance which is created by React router. Using the history instance users can navigate from one URL to another , it also allows user to move back and forth using browser buttons or custom logic.

Methods of useHistory hook :

  • history.push(path) : Navigates to a new URL by pushing it onto the history stack.
  • history.replace(path) : Replaces the current URL in the history stack with the provided path. This can be useful in cases when we don't want to revisit the same page again by navigating backwards.
  • history.goBack() : Navigates to the previous URL in the history stack, similar to brower's backward button.
  • history.goForward() : Navigates to next URl in the history stack, similar to browser's forward button

*Note : "useHistory()" hook will only work in the React-router-dom v5 but not in v6 , as it is replaced with "useNavigate()" hook.

Example: Below is an example of useHistory. Clicking the "Logout " button displays a message ("User logged out ") on to the console and also redirects you to the 'login page'.

JavaScript
import React from 'react'; import { useHistory } from 'react-router-dom';  function Dashboard() {     const history = useHistory();      const handleLogout = () => {         // Simulate some logout logic (e.g., clear user data)         console.log('User logged out');          // Redirect user to login page after logout         history.push('/login');     };      return (         <div>             <h1>Welcome to the Dashboard</h1>             <button onClick={handleLogout}>Logout</button>         </div>     ); }  export default Dashboard; 

Output :

output3-1

outpu3-2
Console view

useRouteMatch

The "useRouteMatch" hook tries to find a match with the current URL and returns an object through which you can access information of the matched route. This information includes paths, url parameters and more.

*Note : "useRouteMatch()" hook will only work in the React-router-dom v5 but not in v6 , as it is replaced with "useMatch()" hook.

Example: Below is an example of useRouteMatch In the above example I've used a URL that is "/posts/:123" which is being compared with the '/posts/:postId ' using "useRouteMatch()" and returns the data present in it.

JavaScript
// App.js  import * as React from "react"; import {     BrowserRouter,     Route,     Routes } from "react-router-dom"; import MyComponent from './MyComponent';  function App() {     return (         <BrowserRouter>             <Routes>                 <Route path="/posts/:postId"                     element={<MyComponent />} />             </Routes>         </BrowserRouter>     ); }  export default App; 
JavaScript
// MyComponent.js  import React from 'react'; import { useParams, useRouteMatch } from 'react-router-dom';  function MyComponent() {     const { postId } = useParams(); // Access URL parameter     const match = useRouteMatch('/posts/:postId'); // Match route pattern      // Display message if route doesn't match pattern     if (!match) {         return <div>This route does not match a blog post.</div>;     }      // Simulate fetching post data (replace with your actual logic)     const postData = {         id: postId,         title: `Blog Post`,         content: 'This is the content of the blog post.'     };      return (         <div>             <h1>PostId {postData.id}</h1>             <h1>{postData.title}</h1>             <p>{postData.content}</p>         </div>     ); }  export default MyComponent; 

Output :
output-4


Next Article
React Router vs. React Router DOM

A

arikirevula_sanjay_praneeth
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

  • What are Protected Routes in React JS ?
    In web development, security is critical when building React applications, especially those handling sensitive data or functionalities, it's crucial to restrict access to certain parts of the application to authorized users only. This is where protected routes come into play. In this article, we wil
    4 min read
  • What are the benefits of using hooks in React-Redux?
    Have you ever wondered how users create amazing websites and apps? Well, in the world of programming, they have some cool tools, and today we're going to explore one of them called "Hooks" in the superhero team of React-Redux. Prerequisites:ReactReact-ReduxReact HooksJavaScriptWhat are Hooks?Hooks a
    2 min read
  • What are React Hooks, and why were they added to React?
    React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components,
    2 min read
  • React Router vs. React Router DOM
    Routing is a fundamental part of any web application. It allows users to move between pages or views. smoothly in traditional web development Routing involves mapping URLs to specific content or views on the server. These are the following topics that we are going to discuss: Table of Content What i
    4 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
  • 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
  • What are the rules of hooks in React, and why are they important?
    In React, hooks empower functional components to utilize state and incorporate other React functionalities seamlessly, enabling a more dynamic and concise development approach. Rules of Hooks in React:Only use hooks at the top level: This means don't use hooks inside loops, conditions, or nested fun
    2 min read
  • Resource Hooks in React
    In React, components often need to access external resources such as data from promises or context information for styling. Managing these resources within the component state could lead to unnecessary complexity and performance overhead. React provides a simple solution with the 'use' hook to overc
    3 min read
  • 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
  • What is react-router-dom ?
    React Router DOM is an npm package that enables you to implement dynamic routing in a web app. It allows you to display pages and allow users to navigate them. It is a fully-featured client and server-side routing library for React. React Router Dom is used to build single-page applications i.e. app
    6 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