![]() |
VOOZH | about |
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.
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:
npm install react-router-dom@nextThe <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>
The useNavigate hook provides a programmatic way to navigate between routes without using <Link> components.
const navigate = useNavigate();The useParams hook allows you to access route parameters directly in functional components.
const { username } = useParams();The useLocation hook enables components to access information about the current URL, such as pathname and search parameters.
const location = useLocation();The useMatch hook allows you to check if the current location matches a specific route pattern.
const match = useMatch('/about');Step 1: Create React app
npx create-react-app router6Step 2: Install React Router v6
npm install react-router-dom@nextUpdated 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"
},
Example:
Steps to run the application: Use the below command in the terminal.
npm startOutput: