Routing with React Router
React Router useParams Hook
useParams reads the dynamic segments of the current URL as an object of strings. A route declared as /internships/:id gives you { id } for the URL /internships/4821.
What is Router useParams Hook in React?
useParams reads the dynamic segments of the current URL as an object of strings. A route declared as /internships/:id gives you { id } for the URL /internships/4821.
Router useParams Hook example
// <Route path="/internships/:id" element={<JobDetail />} />
function JobDetail() {
const { id } = useParams();
const [job, setJob] = useState(null);
useEffect(() => {
fetch(`/api/jobs/${id}`).then(r => r.json()).then(setJob);
}, [id]);
return job ? <h1>{job.title}</h1> : <Spinner />;
}How this works
Listing id in the dependency array matters: navigating from one job to another reuses the same component instance, so only a change in id triggers the new fetch.
Key points to remember
- Every parameter is a string — convert with Number() when you need a number.
- Use useSearchParams for query strings such as ?page=2.
- A missing parameter comes back as undefined, so guard before using it.
Common mistakes with Router useParams Hook
- Omitting id from the effect dependencies, so the page shows stale data after navigating between two detail pages.
- Comparing a string param with a numeric id using ===.
React Router useParams Hook— Interview Questions & FAQs
How do I read query string parameters?+
Use useSearchParams, which returns a URLSearchParams object and a setter: const [params, setParams] = useSearchParams(); params.get("page").
