useRoutes Hook in React Router
Last Updated :
25 Jul, 2024
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 routes in a declarative manner. In this article, we will learn about useRoutes hook with its syntax and example.
What is useRoutes Hook?
useRoutes hook is a part of the React Router library introduced in React Router v6 and is used to define and configure routes in a React application. It provides a flexible approach to defining routing configurations programmatically. It is a functional equivalent of <Routes>. You can define a route configuration JavaScript object that maps specific paths to React components.
Syntax of useRoutes Hook:
import { useRoutes } from 'react-router-dom';
const routeConfig = [
{ path: '/', element: <Home /> },
{ path: '/about', element: <About /> },
// Add more route configurations as needed
];
const App = () => {
const routeResult = useRoutes(routeConfig);
return routeResult;
};
Features of useRoutes Hook?
- It allows you to define routes in a declarative manner using a configuration JavaScript object.
- It allows you to define nested routes.
- It can be defined with dynamic parameters such as product/:id.
- It supports wildcard routes using the * path for handling 404 errors.
Uses of useRoutes Hook
- Making Routes Flexible: It helps you create routes that can change based on what's happening in your app. So, if your app needs to show different pages or components depending on what the user does or what data is available,
useRoutes
can handle that smoothly. - Protecting Routes: If you've got parts of your app that should only be seen by certain users, like maybe admin pages or account settings,
useRoutes
can help you manage who gets to see what. You can use it to check if a user is logged in or has the right permissions before showing certain pages. - Dealing with Tricky Routing: Sometimes, your app's navigation needs to get a bit fancy. Maybe you've got pages within pages, or URLs that change based on what's selected.
useRoutes
is your friend here too. It helps you handle these complex setups and keep your app's navigation smooth and user-friendly.
Installation
To use a useRoutes hook, You have to install a React Router library by using following command:
npm install react-router-dom
Steps to Create Implement useRoutes Hook
Step 1: Create a React application using the following command:
npx create-react-app useroutes
Step 2: After creating your project folder(i.e. gfg), move to it by using the following command:
cd useroutes
Step 3: Install React Router library
npm install react-router-dom
Folder Structure:

Dependencies: The updated dependencies in package.json file will look like.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: This below example demonstrate the use of useRoutes hook.
JavaScript
//src/App.js
import "./App.css";
import { BrowserRouter } from "react-router-dom";
import Router from './router'
export default function App() {
return (
<BrowserRouter>
<div className="App">
<h1 style={{ color: "green" }}>
GeeksForGeeks | useRoutes Example</h1>
<Router />
</div>
</BrowserRouter>
);
}
JavaScript
//src/Navigation.js
import { Link, Outlet } from "react-router-dom";
export default function Navigation() {
return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="about">About</Link>
</li>
<li>
<Link to="course">Course</Link>
</li>
</ul>
</nav>
<Outlet />
</>
);
}
JavaScript
//src/router.js
import { useRoutes } from "react-router-dom";
import Navigation from "./Navigation";
const Home = () => <h1>Home Page</h1>
const About = () => <h1>About Page</h1>
const Course = () => <h1>Course Page</h1>
export default function Router() {
let element = useRoutes([
{
element: <Navigation />,
children: [
{ path: "/", element: <Home /> },
{ path: "about", element: <About /> }
]
},
{
element: <Navigation />,
children: [
{ path: "course", element: <Course /> }
]
},
{
path: '*',
element: <div>404 Not Found</div>
},
]);
return element;
}
To run the application use the following command:
npm run start
Output: Now go to http://localhost:3000 in your browser:
Similar Reads
useLoaderData Hook in React Router
useLoaderData is a hook provided by React Router. React Router is a JavaScript framework that helps to create and handle routing in React applications. This hook helps to fetch the data for the component before it renders, this improves performance and prevents empty states. Data FetchingWithout the
3 min read
Routes Component in React Router
Routes are an integral part of React Router, facilitating the navigation and rendering of components based on URL patterns. In this article, we'll delve into the concept of routes, understanding their role in React Router, and how to define and manage routes effectively. Table of Content What are Ro
4 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
How to use useCounter hook in ReactJS ?
The useCounter is a custom hook provided by the Rooks package for React. It is a counter hook that helps build a simple counter easily and quickly. Syntax: useCounter( initialValue )Parameters: initialValue: It is of number type that describes the initial value.Return Value: counter: It is of type o
2 min read
Route Component in React Router
React Router is a popular library used for managing routing in React applications. At its core lies the Route component, which plays a pivotal role in defining the relationship between URLs and corresponding components. In this article, we'll delve into the intricacies of the Route component, explor
5 min read
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 pa
11 min read
How to use the useHistory hook in React Router?
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
4 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 setup React Router v6 ?
React Router is an amazing library that was created by Remix. The purpose of React Router is to enable Client-Side routing in the React application, that is, by using React Router we can create different routes in our React app and can easily navigate to different pages without even reloading the pa
7 min read
State Hooks in React
State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
3 min read