From React to Next.js: A Transition Guide for Web Wizards

From React to Next.js: A Transition Guide for Web Wizards

Making the Move Seamlessly to Boost Your Development Efficiency

·

5 min read

Problem with ReactJS


Before this we need understand difference between Client Side Rendering(CSR) vs Server Side Rendering(SSR), below is pretty nice video explains the same.

đź’ˇ
In nutshell, CSR(Client Side Rendering) shows an empty page before loading, while SSR(Server Side Rendering) displays a fully-rendered HTML page on the first load.

Below are the real life issues faced using React.

  1. Waterfalling - The initial rendering or the first page load results to a blank screen. While this might not be immediately noticeable, it is one of the limitations in React.

    Here’s another visual explains the same about Client Side Rendering(CSR). Stages are Loading → Skeleton → Full, whereas in Server Side Rendering(SSR) we get Fully-rendered Page.

  2. Lacks SEO Optimization - SEO, or Search Engine Optimization, is the process by which search engines like Google and Bing crawl websites to index/understand what the website is about, this is only possible when website has the content, keywords. The challenge with React is that it delivers content less HTML(like in the image), along with bundle of JavaScript. Thus, indexing is not possible in react.

  3. Doesn’t work where JS can’t be executed(E-MAILs) - In scenarios where JavaScript execution is restricted, such as within email clients like Gmail, client-side JavaScript won't execute. In such cases, it's necessary to send the final or pre-rendered HTML.

Why NextJS ?


đź’ˇ
In Next.js, the key takeaway is that the initial page is server-side rendered, while all subsequent renders follow the standard React rendering process. Technically, each page or route is “pre-rendered” + "hydrated" with ReactJS or JS to make it interactive.

Following are the advantages on using NextJS :

  1. Reduce the bundle size - Since initial page is server-side rendered, large or heavy libraries can be process at backend, thus we can minimize the load on client side.

  2. Backend in NextJS - We don’t separately need an express server we can do this inside the NextJS project. This also results in complete/direct access to backend and files.

  3. No blank page - No blank page on Initial Render, unlike in React application.

đź’ˇ
Keep in Mind: During the initial page load, browser constructs like localStorage and window are not accessible on the server side. localStorage and window object are client side constructs.

Routing


Routing is handled quite differently in NextJS, but it is smooth and easy. Rest 90% is all React. Each page inside pages folder serve as a route.

Index routes

The router will automatically route files named index to the root of the directory.

  • pages/index.js → /

  • pages/blog/index.js → /blog

Nested routes

The router supports nested files. If you create a nested folder structure, files will automatically be routed in the same way still.

  • pages/blog/first-post.js → /blog/first-post

  • pages/dashboard/settings/username.js → /dashboard/settings/username

Pages with Dynamic Routes

Next.js supports pages with dynamic routes. For example, if you create a file called pages/posts/[id].js, then it will be accessible at posts/1, posts/2, etc.

Server Side Rendering


A Basic Code written in Next to understand server side rendering

  1. getServerSideProps Function:

    • This function is special in Next.js, and when it's implemented in a page file, it will run on the server side at build time or during a server request.

    • The function fetches data from an external API (in this case, https://jsonplaceholder.typicode.com/todos/) using the fetch function.

    • The fetched data is then returned as a property (serverRenderedData) inside the props object.

        export async function getServerSideProps() {
          const res = await fetch('https://jsonplaceholder.typicode.com/todos/');
          const data = await res.json();
      
          return {
            props: {
              serverRenderedData: data,
            },
          };
        }
      
  2. Rendering in the Component:

    • The HomePage component receives the serverRenderedData as a prop.

    • It renders the initial HTML on the server side with the fetched data. This HTML is then sent to the client.

        const HomePage = ({ serverRenderedData }) => {
          return (
            <div>
              <h1>Server-Side Rendering with Next.js</h1>
              <ul>
                {serverRenderedData.map((todo) => (
                  <li key={todo.id}>
                    {todo.title} - {todo.completed ? 'Completed' : 'Incomplete'}
                  </li>
                ))}
              </ul>
            </div>
          );
        };
      

The Final Output

Client Side Components vs Server Side Components


  1. Server Side Components (SSR): SSR components are initially rendered on the server before being sent to the client's browser.

    • This approach is used for pages that require dynamic data, SEO optimization, or authentication, as it ensures that the content is available when the page is loaded.

    • SSR is beneficial for improving SEO and ensuring content is visible to search engines.

  2. Client Side Components (CSR): CSR components are initially rendered in the client's browser using JavaScript.

    • This approach is suitable for pages that don't require SEO optimization, involve dynamic client-side interactions, or have content that can be loaded after the initial page render.

    • CSR is more interactive and can be quicker for navigating between pages within the application.

    • Add "use client" at the top of each page where you don't want Server Side Components.

Next.js allows you to use a combination of both SSR and CSR, choosing the most appropriate rendering method for different parts of your application to achieve a balance between performance and functionality.

Conclusion


In conclusion, this journey from React to NextJS has unveiled a plethora of blessings that could substantially increase your internet development revel in. We've delved into the seamless transition manner, unlocking the ability of server-aspect rendering (SSR) . To recap, NextJS now not only simplifies the setup and configuration however also complements overall performance, search engine marketing, and usual development efficiency. As web builders, the encouragement to discover NextJS is rooted in its ability to strike a balance among powerful functions and developer-pleasant conventions. Embrace the transition with self assurance, and witness how NextJS empowers you to build scalable, high-overall performance internet applications. As you embark in this exciting journey, preserve pushing the bounds of what is possible inside the dynamic panorama of web improvement. Happy coding!

Â