In a nested route structure like `/users/:userId/posts/:postId`, how can a deeply nested component rendering for a specific post access the `userId`?

React JS interview question for Advanced practice.

Answer

By calling the useParams hook, which returns an object containing all dynamic parameters from the entire matched URL.

Explanation

The useParams hook consolidates all dynamic parameters from all matched route segments into a single object. In the given example, a component rendered at /users/123/posts/456 would receive { userId: '123', postId: '456' } from a single call to useParams(). There is no need to drill props or use a different hook.

Related Questions