Dynamic URL Parameters with useParams
Dynamic URL Parameters with useParams
1. The Need for Dynamic Route Segments
In modern web applications, you cannot hardcode a separate route for every piece of content in your database:
/courses/react-for-beginners/courses/django-backend-architecture/courses/data-analysis-mastery
Creating hundreds of static route tags (<Route path="/courses/course-1" />, <Route path="/courses/course-2" />) is impossible.
Instead, routers use Dynamic URL Parameters (denoted with a leading colon :):
The :courseSlug segment acts as a wildcard variable that captures whatever string occupies that position in the active URL.
2. Defining Dynamic Routes
In your router definition, place a colon : before the parameter name:
3. Reading Parameters with the useParams Hook
React Router provides the useParams() hook to extract active URL parameters from inside the rendered component.
useParams() returns an object where keys match the param names defined in your route (:courseSlug -> params.courseSlug):
4. Crucial Hook Rule: Dependency on useParams
Notice line 29: [courseSlug] is included in the useEffect dependency array.
If a user navigates directly from /courses/react-for-beginners to /courses/django-backend, the CourseDetail component does not unmount and remount; only its URL parameter changes! Listing courseSlug in the dependency array guarantees that your data-fetching effect fires again to load the new course data.
Practice Quiz
<Route> path?useParams() hook return?/users/:userId/posts/:postId and the active URL is /users/42/posts/108, what will useParams() return?courseSlug) be included in the useEffect dependency array?useParams object?Programmatic Navigation and useSearchParams
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Defining Routes, Route Layouts, and Outlets | Programmatic Navigation and useSearchParams |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.