Challenge your understanding of Next.js dynamic routing, including file-based routing, dynamic segments, and handling URL parameters in JavaScript frameworks. Perfect for developers refining their grasp of modern web application navigation and data flow.
In Next.js, which file naming convention allows you to create a dynamic route segment for user profiles at '/users/[id]'?
Explanation: The square bracket syntax [id].js indicates a dynamic route segment in Next.js, enabling URLs like '/users/123' to be matched by this file. Braces ({id}.js) and parentheses ((id).js) are not recognized by the routing system and would not create dynamic segments. Using 'user_id.js' would create a static route for '/users/user_id', not a dynamic segment for any user.
How would you retrieve the 'slug' parameter from the URL in a page rendered for '/posts/[slug]' using hooks in a functional component?
Explanation: The useRouter hook from 'next/router' provides access to the router object, including any dynamic parameters such as 'slug'. getInitialProps can pass parameters via props but is not a hook. Reading window.location.search would not capture path parameters, only query strings. useParams is not available in this routing system and is associated with another library.
Which file should you create to handle a catch-all route for product categories like '/categories/electronics/phones'?
Explanation: Files named with the ellipsis syntax '[...slug].js' capture all additional segments as an array, allowing flexible matching such as '/categories/electronics/phones'. '[slug...].js' and '[slug*].js' are invalid syntaxes. 'slug.js' would only match a single segment like '/categories/phones', not multiple nested segments.
What is the primary benefit of using shallow routing when updating the URL query parameters in a Next.js application?
Explanation: Shallow routing allows you to update the route URL and state without triggering data fetches such as getServerSideProps or getStaticProps, which improves performance. It does not force a full page refresh or reload components entirely, and while it keeps state synced, it does not automatically merge any unrelated state.
Suppose you create an API file at 'pages/api/posts/[postId].js'. What URLs will this API route handle?
Explanation: With the '[postId].js' filename, the API route matches any URL that supplies a value for 'postId' as part of the path, such as '/api/posts/42'. It will not match '/api/posts' (no parameter), '/api/posts-42' (incorrect structure), or '/api/posts?postId=42' (uses a query string rather than a path segment).