React Router v5 vs v6: Key Differences Explained
Md Yusuf
Posted on September 30, 2024
React Router v6 introduced significant improvements and changes compared to v5. Here’s a breakdown of the key differences:
1. Switch
vs Routes
-
v5: Uses
Switch
to wrap your routes.
<Switch>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
-
v6: Replaces
Switch
withRoutes
, andcomponent
is replaced withelement
which requires JSX.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
2. No More exact
Prop
-
v5: You need the
exact
prop to avoid partial matches in routes.
<Route path="/" exact component={Home} />
-
v6: All routes are exact by default, so no need for the
exact
prop anymore.
3. Nested Routes
-
v5: Nested routes are created by placing
Route
components inside the parent’s component.
function App() {
return (
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/dashboard/settings" component={Settings} />
</Switch>
);
}
-
v6: Nested routes are directly declared within the
Routes
structure.
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
4. useNavigate
vs useHistory
-
v5:
useHistory()
was used for programmatic navigation.
const history = useHistory();
history.push('/about');
-
v6: Replaces
useHistory
withuseNavigate()
.
const navigate = useNavigate();
navigate('/about');
5. Route Rendering Methods
-
v5: You could use
component
,render
, orchildren
props to render components.
<Route path="/" component={Home} />
<Route path="/about" render={() => <About />} />
-
v6: Removes
component
andrender
. You now use onlyelement
for JSX rendering.
<Route path="/" element={<Home />} />
6. Relative Routes
- v5: When navigating, you needed to construct absolute paths.
<Link to="/dashboard/settings">Settings</Link>
- v6: Supports relative paths based on the current route.
<Link to="settings">Settings</Link>
7. Redirect
vs Navigate
-
v5: Used the
Redirect
component to handle route redirects.
<Redirect to="/login" />
-
v6: Replaces
Redirect
withNavigate
.
<Navigate to="/login" />
8. Hooks API Improvements
-
v6: Simplified hooks, like
useParams
,useNavigate
,useRoutes
for greater flexibility.
Summary of Key Changes:
-
Switch
replaced byRoutes
. -
exact
prop no longer needed. - More intuitive nested routes structure.
-
useHistory
replaced byuseNavigate
. - Routes are rendered using the
element
prop exclusively.
These changes streamline the API and make route handling simpler in React Router v6.
💖 💪 🙅 🚩
Md Yusuf
Posted on September 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.