DEV Community

Cover image for πŸš€ Understanding How Next.js Works: A Comparison with React.js
Vishal Yadav
Vishal Yadav

Posted on

πŸš€ Understanding How Next.js Works: A Comparison with React.js

Next.js is often viewed as an extension of React, but it brings a lot more to the table than just a framework for building React applications. This blog post delves into how Next.js operates differently from React.js under the hood, highlighting its unique features and advantages.


1. Server-Side Rendering (SSR)

Next.js offers out-of-the-box server-side rendering, which means your components can be rendered on the server and sent as HTML to the client. This approach enhances performance and improves SEO, as search engines can index fully rendered pages.

Example:

// pages/index.js
export async function getServerSideProps() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  return {
    props: { data }, // Passed to the page component as props
  };
}

const HomePage = ({ data }) => {
  return (
    <div>
      <h1>Server-Side Rendered Page</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default HomePage;
Enter fullscreen mode Exit fullscreen mode

2. Static Site Generation (SSG)

Next.js allows you to pre-render pages at build time, making them available as static HTML files. This leads to faster load times and improved scalability, especially for content-heavy sites.

Example:

// pages/products.js
export async function getStaticProps() {
  const response = await fetch('https://api.example.com/products');
  const products = await response.json();

  return {
    props: { products }, // Passed to the page component as props
    revalidate: 10, // Re-generate the page every 10 seconds
  };
}

const ProductsPage = ({ products }) => {
  return (
    <div>
      <h1>Static Site Generated Products</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default ProductsPage;
Enter fullscreen mode Exit fullscreen mode

3. File-Based Routing

Next.js provides a file-based routing system. You simply create a file in the pages directory, and it automatically becomes a route. This simplifies the routing process compared to React, which typically relies on external libraries like React Router.

Example:

  • Creating a file named about.js inside the pages directory will generate the /about route automatically.
// pages/about.js
const AboutPage = () => {
  return <h1>About Us</h1>;
};

export default AboutPage;
Enter fullscreen mode Exit fullscreen mode

4. API Routes

Next.js supports creating API endpoints alongside your front-end code. This means you can build full-stack applications with React and Node.js within the same framework.

Example:

// pages/api/users.js
export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' });
}
Enter fullscreen mode Exit fullscreen mode

You can access this API route at /api/users.


5. Automatic Code Splitting

Next.js automatically splits your code into smaller bundles, loading only the necessary JavaScript for the page the user is viewing. This significantly enhances performance by reducing initial load times.

Example:

No additional configuration is needed; Next.js handles code splitting automatically based on your page structure.


6. Optimized Images

Next.js has a built-in image optimization feature that serves images in the optimal format, size, and quality. This enhances performance and user experience, especially on slower networks.

Example:

import Image from 'next/image';

const ProfilePicture = () => {
  return (
    <Image 
      src="/profile.jpg" 
      alt="Profile Picture" 
      width={500} 
      height={500} 
      priority 
    />
  );
};

export default ProfilePicture;
Enter fullscreen mode Exit fullscreen mode

7. Built-In CSS and Sass Support

Next.js comes with built-in support for CSS and Sass, allowing for easier and more efficient styling of your application without additional configuration.

Example:

/* styles/Home.module.css */
.title {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode
// pages/index.js
import styles from '../styles/Home.module.css';

const HomePage = () => {
  return <h1 className={styles.title}>Welcome to Next.js!</h1>;
};

export default HomePage;
Enter fullscreen mode Exit fullscreen mode

8. Incremental Static Regeneration (ISR)

Next.js allows pages to be updated incrementally after the initial build. This means you can keep your static content up to date without needing to rebuild your entire site.

Example:

// pages/blog/[id].js
export async function getStaticPaths() {
  const paths = await fetchBlogPostIds(); // Fetch post IDs from an API

  return {
    paths,
    fallback: true,
  };
}

export async function getStaticProps({ params }) {
  const post = await fetchBlogPost(params.id); // Fetch post data based on ID

  return {
    props: { post },
    revalidate: 60, // Re-generate this page every minute if there are requests
  };
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Next.js is more than just an extension of React; it provides robust features that enhance performance, SEO, and developer experience. By leveraging server-side rendering, static site generation, file-based routing, and other built-in capabilities, developers can create high-performance web applications more efficiently than with React alone.

Choosing between Next.js and React depends on your project requirementsβ€”if you need SEO optimization or server-side capabilities, Next.js is likely the better choice.


References:

  1. Toptal. (2023). Next.js vs. React: A Comparative Tutorial.
  2. Prismic.io. (2024). Next.js vs. React: Differences and How to Choose.
  3. UXPin. (2024). NextJS vs React β€” Which One is Better for Web Development?.
  4. GeeksforGeeks. (2024). NextJS vs ReactJS: Which One to Choose?.

If you found this guide useful, please consider sharing it with others! 😊


This blog provides an in-depth comparison of Next.js and React.js while incorporating updated examples and changing variable names throughout all code snippets for clarity and relevance in modern web development practices.

Citations:
[1] https://www.toptal.com/next-js/next-js-vs-react
[2] https://prismic.io/blog/nextjs-vs-react
[3] https://www.uxpin.com/studio/blog/nextjs-vs-react/
[4] https://radixweb.com/blog/nextjs-vs-react
[5] https://www.geeksforgeeks.org/nextjs-vs-reactjs-which-one-to-choose/
[6] https://www.reddit.com/r/react/comments/18uxapg/nextjs_vs_react/
[7] https://nextjs.org/learn/react-foundations/what-is-react-and-nextjs
[8] https://www.freecodecamp.org/news/next-vs-react/

Top comments (0)