Dynamic Routing in React: useParams and Route Parameters
Dynamic routing lets one component handle many URLs. Here is how route parameters work and how to read them.
Dynamic Routing in React: useParams and Route Parameters
Dynamic routing is what lets one component handle many similar URLs, like a product page for any product id. Here is how it works.
What Dynamic Routing Is
Instead of a fixed path like /about, a dynamic route has a parameter, like /product/:id. The same component renders for any id, and you read the id to fetch the right data.
Defining a Dynamic Route
In your route path, use a colon followed by the parameter name, like /restaurant/:id. React Router matches any value in that position and makes it available as a parameter.
Reading the Parameter
Use the useParams hook inside the component to read the parameter. It returns an object with the parameter name and its value from the URL.
Using the Parameter to Fetch
Pass the parameter to your fetch call so the component loads the right data. Include the parameter in the useEffect dependency array so the fetch re-runs when the id changes.
Multiple Parameters
You can have multiple parameters, like /user/:userId/post/:postId. useParams returns all of them in one object.
The Common Mistake
Forgetting to add the parameter to the useEffect dependency array, so navigating between two dynamic routes does not refetch the data and shows stale content.
The Takeaway
Dynamic routing uses a colon parameter in the path, useParams reads it, and you pass it to your fetch with the parameter in the dependency array. This lets one component handle many URLs.
A dynamic route uses a parameter in the path, like /product/:id. The same component renders for any id, and you read the id with useParams to fetch the right data. This lets one component handle many similar URLs.
Use the useParams hook inside the component. It returns an object with the parameter name and its value from the URL, which you can then use to fetch the right data.
In the route path, use a colon followed by the parameter name, like /restaurant/:id. React Router matches any value in that position and makes it available as a parameter through useParams.
Because you forgot to add the parameter to the useEffect dependency array. Without it, the effect does not re-run when navigating between two dynamic routes, so the component shows stale data for the previous id.
Yes, like /user/:userId/post/:postId. useParams returns all parameters in one object, so you can read both the userId and postId inside the component.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

