How to Update useParams Hook in React Router
In React applications using React Router, the useParams
hook is used to retrieve dynamic parameters from the current URL.
Because useParams is a read-only hook that reflects the
active route, you cannot update its state directly using a setter
function. Instead, to update the values returned by
useParams, you must navigate to a new URL path using the
useNavigate hook or a navigation component, which
automatically triggers a re-render with the updated parameter
values.
The Concept: Updating URL Parameters
The useParams hook acts as a listener to the URL. It
does not have an internal state setter like useState.
Therefore, the only way to “update” the parameters is to change the
browser’s address. When the route changes, React Router matches the new
path, updates the history stack, and provides the new parameter values
to your component.
Step-by-Step Implementation
To update a URL parameter, follow these steps:
- Import
useParamsanduseNavigatefromreact-router-dom. - Retrieve the current parameters using
useParams(). - Use the
useNavigate()hook to get the navigation function. - Call the navigation function with the new URL path containing the updated parameter.
Code Example
Here is a practical example demonstrating how to update a
userId parameter programmatically.
import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
function UserProfile() {
// 1. Retrieve the current dynamic parameter (e.g., /user/:userId)
const { userId } = useParams();
// 2. Initialize the navigate function
const navigate = useNavigate();
const handleNextUser = () => {
// Calculate the next ID
const nextUserId = parseInt(userId, 10) + 1;
// 3. Update the URL. This will trigger useParams to return the new value.
navigate(`/user/${nextUserId}`);
};
return (
<div>
<h2>User Profile</h2>
<p>Current User ID: <strong>{userId}</strong></p>
<button onClick={handleNextUser}>
Go to Next User
</button>
</div>
);
}
export default UserProfile;Using Links for Updates
If the update is triggered by a user click rather than a programmatic
event, you should use the <Link> or
<NavLink> component. This is better for accessibility
and SEO.
import { Link, useParams } from 'react-router-dom';
function UserNavigation() {
const { userId } = useParams();
const nextUserId = parseInt(userId, 10) + 1;
return (
<Link to={`/user/${nextUserId}`}>
View Next User Profile
</Link>
);
}By changing the URL via useNavigate or
Link, React Router updates the route context, causing
useParams to return the new parameter values on the
subsequent render.