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:
How to Integrate React Router with Remix?
Next article icon

Migrate to React Router v6

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

React Router v6 brings significant changes and improvements over its predecessor, offering a more intuitive API and better performance. Migrating to React Router v6 might seem daunting, but with proper guidance, the transition can be smooth and beneficial for your React applications.

Enhancements in React Router v6

React Router v6 introduces several key enhancements and changes that greatly improve the routing experience in React applications. Here's a deeper dive into the improvements:

  • Simplified API: React Router v6 streamlines the API, making it more intuitive and easier to understand.
  • Improved Nesting: With v6, nesting routes become more straightforward and flexible.
  • Hooks-based Navigation: React Router v6 embraces React's hook-based architecture by introducing hooks for navigation.
  • Dynamic Route Parameters: Handling dynamic route parameters is made simpler with the `useParams` hook.
  • Enhanced Performance: The new architecture ensures efficient navigation and minimal overhead, contributing to a smoother user experience, especially in large-scale applications.
  • TypeScript Support: React Router v6 offers improved TypeScript support, with enhanced type definitions and better integration with TypeScript projects.

Install React Router v6

npm install react-router-dom@next

Features

Using the <Routes> Component for Routing:

The <Routes> component is the new way to define routes in React Router v6. It replaces the combination of <Switch> and <Route> components used in previous versions.

 <Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>

Leveraging the useNavigate Hook for Navigation:

The useNavigate hook provides a programmatic way to navigate between routes without using <Link> components.

 const navigate = useNavigate();

Adopting the useParams Hook for Accessing Route Parameters:

The useParams hook allows you to access route parameters directly in functional components.

const { username } = useParams();

Employing the useLocation Hook for Accessing the Current Location

The useLocation hook enables components to access information about the current URL, such as pathname and search parameters.

const location = useLocation();

Utilizing the useMatch Hook for Matching Routes:

The useMatch hook allows you to check if the current location matches a specific route pattern.

const match = useMatch('/about');

Steps to implement React Router v6

Step 1: Create React app

npx create-react-app router6

Step 2: Install React Router v6

npm install react-router-dom@next

Updated Dependencies in package.json File:

  "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.0.0-beta.0"
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Project Structure:

Screenshot-2024-04-25-112847
project structure

Example:

JavaScript
// Filename - App.js  import React from 'react'; import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; import { useNavigate, useParams, useLocation, useMatch } from 'react-router-dom';  function App() {   return (     <Router>       <nav>         <ul>           <li>             <Link to="/">Home</Link>           </li>           <li>             <Link to="/about">About</Link>           </li>           <li>             <Link to="/profile/john">Profile</Link>           </li>         </ul>       </nav>       <Routes>         <Route path="/" element={<Home />} />         <Route path="/about" element={<About />} />         <Route path="/profile/:username" element={<Profile />} />         <Route path="*" element={<NotFound />} />       </Routes>     </Router>   ); }  function Home() {   return <h1>Welcome to the Home Page!</h1>; }  function About() {   return <h1>About Page</h1>; }  function Profile() {   const { username } = useParams();   const location = useLocation();   const navigate = useNavigate();   const matchAbout = useMatch('/about');    const handleButtonClick = () => {     navigate('/');   };    return (     <div>       <h1>User Profile: {username}</h1>       <p>Current URL: {location.pathname}</p>       <button onClick={handleButtonClick}>Go to Home</button>       {matchAbout && <p>This is the About page!</p>}     </div>   ); }  function NotFound() {   return <h1>404 - Not Found</h1>; }  export default App; 

Steps to run the application: Use the below command in the terminal.

npm start

Output:

Recording-2024-04-25-113034-(1)
output

Next Article
How to Integrate React Router with Remix?

I

intellige698j
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • ReactJS-Router

Similar Reads

  • 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
  • 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
  • How to Integrate React Router with Remix?
    Integrating React Router with Remix includes the usage of Remix's integrated router abilities thinking that Remix already uses React Router as its foundation. However, if you want to go beyond number one routing and leverage several React Router's extra precise or advanced skills. You may integrate
    7 min read
  • React Router V5 vs V6
    React Router is widely appreciated in React apps for handling routing and navigation. It provides a way to configure routes. Show components based on the current URL. The newest release, React Router v6 introduces changes and improvements compared to the version of React Router v5. This article will
    7 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
  • Next.js Migrating from React Router
    Are you using React Router in your web application and planning to switch to Next.js? Don't worry, the migration process is easy and we've got you covered! This blog post will guide you through the process and help you understand the benefits of doing so. What is Next.js? Next.js is a React-based fr
    5 min read
  • Create a basic Navbar using React Router v6
    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. Rea
    5 min read
  • React Router Tutorial
    React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. With React Router, you can create a single-page application (SPA) with multiple "pages"
    3 min read
  • 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. Thi
    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