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:
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.
Hooks Of React Router 5:
These are 4 React Router Hooks in v 5 that you can use in your React applications:
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 pageCheck 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 iduseRouteMatch 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>;
}
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
8 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
6 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects