< Back to blog

2024-05-15

Building SPAs - Choose Next.js Over React!

https://graphql.maplecms.ai/api/v1/project/8a49de2b-6763-4d32-8cd1-e9f805991fec/storage/next-vs-reactjs.png

Introduction

As an avid front-end developer, I've been a huge fan of React for a long time. However, I must admit that Next.js has significantly grown on me, especially for Single Page Applications (SPAs) - in fact, it's particularly for them!

In this post, we're going to explore why Next.js should be your preferred choice over React for virtually any web project.


Preface

Before delving deeper, it's important to clarify the context of my recommendation. When I advocate for Next.js, I'm specifically referring to a combination of Static Site Generation (SSG) and Client Side Rendering (CSR), as opposed to relying solely on CSR, which is a common approach in React applications. This hybrid methodology harnesses the best of both worlds: the efficiency of SSG and the dynamic, interactive nature of CSR. This strategic blend not only enhances performance but also optimizes user experience, making Next.js a potent framework for modern web development.


Building the Entire Page

React mounts itself onto a specific div. Next.js, on the other hand, can build the entire page. This makes a huge difference for me, because with React you have the <html>, <title>, and other tags at the mercy of some external index.html file or are constrained within a single root div. In contrast, Next.js allows you to control the entire HTML structure directly within your JavaScript code. This provides a more integrated approach, allowing for control and flexibility:


  • Sometimes, you may need to include external scripts or widgets from third-party services like analytics, chatbots, or social media integrations. Having control over the entire page structure allows you to place these scripts exactly where you need them, ensuring they load correctly.
  • Controlling the <html lang="?"> is also useful for internalization purposes. Dynamically set user's preferences or geographical location. Helps provide localized content and also assists screen readers in understanding the language of the content.
  • Ease optimization of fonts using <link rel="preload"> for example.
  • And the list goes on


Avoid the White Screen During Loading

A common challenge for seasoned React developers is the dreaded "White Screen" - a brief but noticeable period when the app initially loads, displaying nothing but a blank, white screen. This issue typically arises as your application grows in size and complexity, leading to longer loading times that can detract from the professional appearance and user experience of your app.


While in a standard React setup, a workaround is to manually break your app into smaller bundles to optimize load times, this process can be complex and time-consuming. Enter Next.js, where this issue is elegantly addressed right out of the box. In Next.js, every page is inherently treated as an individual bundle. This means that the framework automatically manages the process of splitting and serving these bundles, ensuring that users receive only the code they need for the page they are visiting.


More Resilience

Static Site Generation (SSG) in Next.js helps make websites more reliable. Usually, web pages are made right in the user's browser, which can be slow or even fail if the rendering logic is faulty. But with SSG, pages are created beforehand, during the build process. This means you have a higher chance to detect an issue before it reaches the user, during build time.

Also, the following code will cause the react app to "crash" - because there is no error handling, but for a nextapp, it will just cause an error to printed to the log.


// faulty useEffect
func MyComponent() {
  useEffect() {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => setData(data));
      // Missing error handling here
   }, [])
}

And yes, you can achieve the same by adding an error handler, but still that is an extra development effort you would need to put in.


That Being Said, There are Also Caveats

  • Hydration issues - Mismatches between server-side and client-side rendering. This can be very common once you create some dynamic JSX per user or based on some logic. Thankfully, it can be easy to fix by introducing a useEffect that sets some state and making rendering dependent on that state. This way, this rendering part will occur on the browser.
  • The same issue arises with 3rd parties that are React-nice but are not Nextjs-nice. Worst case scenario is if a third-party component doesn't work in Nextjs, then you can just wrap it with a wrapper component, and import it using dynamic


// RichTextEditor.tsx:
import React from 'react'
import dynamic from 'next/dynamic'

// RichTextEditorNoSRR defined in its own file uses a 3rd party RichTextEditor that doesn't work well with SRR
// So this wrapper solves this issue by deferring the rendering to client-side only
const RichTextEditorNoSSR = dynamic(() => import('./RichTextEditorNoSSR'), { ssr: false })

export default function RichTextEditor({ value, onChange }: { value: string, onChange: (e: string) => void }) {
    return (
        <RichTextEditorNoSSR value={value} onChange={onChange} />
    )
}


Conclusion

Next.js stands as a compelling choice for modern web development. Its ability to build entire pages, eliminate the white screen problem, and enhance resilience through Static Site Generation makes it a powerful alternative to React. Please be warned if you choose to go with this solution, since like I mentioned there might be some caveats and some things working out of the box in react might not work for you, and you will hate the minute your read this post.

But for me the benefits outweigh the drawbacks. Plus, you will be in good company - last time I checked OpenAI's webapp is Nextjs, and of course Maple CMS is too.

So give it a try and experience the difference for yourself. Happy coding!

Maple CMS Logo

Ready to Get a Taste of a Sweeter Future?

"I was able to get my website up and running in less than 10 minutes! Maple CMS is truly a headless CMS that works for you!"