Dynamic Routes in Next.js

Dynamic routes allow you to create pages based on URL parameters, useful for generating unique content like product pages or user profiles.

Using this approach allows for better scalability, flexibility, and efficiency in your applications. It helps in organizing code, improving performance, and ensuring seamless content updates.

Creating a Dynamic Route

Inside pages/, create a folder with square brackets:

pages/post/[id].js

Then, use useRouter to access the dynamic parameter:

import { useRouter } from 'next/router';

export default function Post() {
  const router = useRouter();
  const { id } = router.query;

  return <h1>Post ID: {id}</h1>;
}

Fetching Data for Dynamic Pages

export async function getServerSideProps(context) {
 const { id } = context.params;
 return { props: { id } };
}

Conclusion

Dynamic routes make it easy to create URL-based pages that update automatically based on incoming data, ideal for content-heavy applications.

Leave a comment

Your email address will not be published. Required fields are marked *