Day 2: Mastering Dynamic Routing and Data Fetching in Next.js ??
Kshitish Kumar Pothal
Next Js || React js || Frontend Developer || Wix || DSA || 500+ DSA Problem Solved || Java || Python || Kotlin || AWS
Welcome back to Day 2 of our journey to becoming Next.js pros! Today, we tackled two essential topics that form the backbone of dynamic, high-performance web applications: Dynamic Routing and Data Fetching. Let’s dive right in!
Dynamic Routing in Next.js
Dynamic routing allows us to create pages with routes based on parameters. For example, if you're building a blog, you want a route like /blog/[id] for individual posts. Here's how you can do it:
// File: pages/blog/[id].js
import { useRouter } from 'next/router';
export default function BlogPost() {
const router = useRouter();
const { id } = router.query;
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>Blog Post ID: {id}</h1>
<p>Welcome to the blog post with ID: {id}!</p>
</div>
);
}
Now, visiting /blog/1 or /blog/42 will dynamically render the page based on the id parameter.
For better performance and SEO, you can statically generate dynamic routes during the build:
export async function getStaticPaths() {
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } },
],
fallback: false,
};
}
export async function getStaticProps({ params }) {
return { props: { id: params.id } };
}
export default function BlogPost({ id }) {
return <h1>Pre-rendered Blog Post ID: {id}</h1>;
}
Data Fetching Techniques
Next.js provides three main ways to fetch data:
Fetch data at build time for pages that don’t change often.
Fetch data on every request for dynamic, frequently updated content.
Fetch data on the client using libraries like fetch or axios for interactive experiences.
Example of getServerSideProps:
export async function getServerSideProps(context) {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
return { props: { post: data } };
}
export default function BlogPost({ post }) {
return (
<div style={{ padding: "20px" }}>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
What’s Next?
Tomorrow, we’ll unlock the power of API routes and explore how Next.js makes full-stack development seamless by integrating backend logic into the same framework.
Are you building along with me? Share your progress or questions in the comments below. Let’s keep growing together!
#Nextjs #WebDevelopment #React #DynamicRouting #DataFetching