Apr 14

The most recent iterations of React and Next.js provide ground-breaking capabilities such as server components. Now that React 18 and Next.js 13 are available, developers may render components on the server for greater performance, a better user experience, and easier development workflows. We will go into the idea of server components in this post, examining how they operate, their advantages, and how they may be used in React and Next.js apps. By the conclusion, you will have a thorough grasp of server components and how they could fundamentally alter how we create online apps.

Understanding Server Components & Client Components

Server Components

The server component refers to these frameworks’ server-side rendering (SSR) capabilities. Instead of delivering only JavaScript code, SSR enables you to render your React components on the server and send the resulting HTML to the client.

It refers to libraries or modules in React.js, like ReactDOMServer, that enable server-side rendering. With server-side rendering, the server may create the first HTML markup for the desired React components and deliver it to the client when a request is made to the server. This aids in enhancing your application’s initial load time and SEO friendliness. As opposed to React.js, Next.js is a framework that is developed on top of it and has built-in server-side rendering features. A file-based routing system and automatic code splitting are only two of the features that make the setup of SSR easier. You may build pages using Next.js that are rendered on the server and sent as fully rendered HTML to the client.

Using unique functions like “getServerSideProps” or “getInitialProps,” the server component in Next.js can be defined. Before rendering the React component, you can fetch data or carry out server-side activities using these functions, which are carried out on the server. These functions allow the user to provide data back to the relevant React component as props. Your React.js and Next.js applications will run more quickly, perform better in search engine results, and offer a better user experience if you employ server-side rendering.

Client Components

The portion of the program that runs in the client’s web browser is referred to as the client component. It is in charge of managing user interactions and rendering the user interface.

The client component in React.js typically comprises of React components that specify the layout and functionality of the user interface. These JavaScript-written elements can be combined to build intricate user interfaces. To efficiently update the real DOM (Document Object Model) in response to changes in component state and properties, React uses a virtual DOM (Document Object Model).

A framework based on React.js called Next.js expands on the idea of the client component. In Next.js, the client component can support both static site generation (SSG) and server-side rendering (SSR). According to the configuration, the client component may either be pre-rendered on the server and supplied as static HTML or it may be rendered on the client side. Building complicated React apps is made simpler by the fact that Next.js comes with functionality like data fetching, routing, and server-side rendering.

Overall, rendering the UI and managing user interactions on the client side of a web application are the responsibilities of the client component in both React.js and Next.js. It is a crucial component in creating dynamic and interactive user interfaces with these frameworks.

Server Components’ Advantages

  • Enhanced Performance: Server components significantly reduce the time it takes for web apps to load initially, giving them a snappier and more responsive feel. Even on slow connections, users can access the material more quickly by offloading rendering to the server.
  • Improved SEO: A crucial component of search engine optimization is the server. Since HTML content is what search engine crawlers primarily read, rendering components on the server guarantees that the content of your application can be quickly accessed and indexed by the search engines, increasing its exposure in search results.
  • Better User Experiences: Server components give users a faster, more fluid experience by cutting down on the time it takes for the first render. The application may be used by users more quickly, increasing engagement and happiness.

Server Component Implementation in Next and React.js

Server components are supported by both React 18 and Next.js 13, allowing programmers to take advantage of this useful function in their creations. Here’s how to add server components to your projects using React and Next.js.:

  • Setting Up the Environment: Ensure that Next.js 13 and React 18 are installed in your project before using server components. Update your dependencies and make the appropriate changes to your development environment.
  • How to Define Server Components in React: The ‘react-server-dom’ package is used to define server components in React. Similar to conventional React components, but with a few minor variations, server components can be created. Hooks, lifecycle methods, and stateful server components are all possibilities. They must not, however, include any client-side-specific logic.
  • Server-Side Rendering: Using the ‘next/server’ package of Next.js, server components can be rendered on the server. You can construct a server instance and render server components inside of it by importing the ‘createComponentServer’ function. Sending the HTML to the client and managing the server-side rendering process are handled by Next.js.
  • Communication with Server Components: Props and events are used to facilitate communication between client-side and server components. Props, which can be supplied from client-side components or received from other APIs, allow server components to accept data. The seamless connection between the two is made possible by the ability of server components to send events that cause client-side components to take action.

Wrapping Up

Server Components in React 18 and Next.js 13 represent a significant leap forward in the world of web development. By enabling server-side rendering of components, they address performance bottlenecks and provide a more efficient way to build interactive and scalable web applications. As we embrace this new paradigm, it is crucial to understand the concepts, benefits, and implementation strategies to take full advantage of Server Components’ potential. With React’s commitment to innovation and community support, we can expect exciting advancements and further refinement of Server Components in the future.

Tags: , , , ,

May 15

React 18 was released in March 2022. Officially, React 18 is now ready to use! This release focuses on performance improvements and updating the rendering engine. React 18 sets the foundation for concurrent rendering APIs that future React features will be built on top of.

In my opinion, the latest feature that revolutionized the React Ecosystem was React Hooks, introduced in React 16.8 back in 2019. Since then, we have seen many versions being released. But without any major changes, what will happen in React 18? In this tutorial, we will have a quick look at the features released in React 18, and explain a few major concepts such as concurrent rendering, automatic batching, and transitions.

New Features

Automatic Batching

React 18 features automatic batching. To understand batching, let’s consider the example of grocery shopping from the same React Working Group discussion.

Let’s say that you are making pasta for dinner. If you were to optimize your grocery trip, you would create a list of all the ingredients that you need to buy, make a trip to the grocery store, and get all your ingredients in one trip. This is batching.

Without batching, you would start cooking, find out you need an ingredient, go to the grocery store and buy the ingredient. When you come back and continue cooking, you’ll find out you need another ingredient, you’ll then go to the grocery store again to buy that ingredient

In React, batching helps to reduce the number of re-renders that happen when a state changes, when you call setState. With this new exciting feature, React will combine multiple setState() calls into a single re-render to improve performance. Before this, if we had multiple setState() inside of a setTimeout(), React will re-render for every state update which sometimes causes performance issues if we have larger components. Previously, React batched state updates in event handlers.

You may already be familiar with this. This feature was available in React 17, but now it comes out of the box.

// React 17
  setTimeout(() => {
    setCount(c => c + 1);
    setFlag(f => !f);
    // The component will be rendered twice.
  }, 1000);


// React 18
  setTimeout(() => {
    setCount(c => c + 1);
    setFlag(f => !f);
    // The component will be rendered only once.
  }, 1000);

Transitions

This new feature lets the dev split the state update into two categories: urgent and low priority.

Transitions can be used to mark UI updates that do not need urgent resources for updating. For some actions, like selecting in a dropdown or updating an input, you want the action to respond immediately, so now we could distinguish between an urgent update and a non-urgent one. These non-urgent updates are called transitions. By marking non-urgent UI updates as “transitions”, React will know which updates to prioritize. This makes it easier to optimize rendering and get rid of stale rendering.

Updates wrapped in startTransition are handled as non-urgent and will be interrupted if more urgent updates like clicks or keypresses come in.

import { startTransition } from 'react';

// Updating state with urgent priority
setInputValue(input);

// Inside startTransition the updates won't be urgent
// and can be interrupted
startTransition(() => {
  setSearchQuery(input);
});

New Suspense Features

Finally, we will have Suspense on the server. In the server-rendered apps, we will have only one Suspense API.

In a client-rendered app, you load the HTML of your page from the server along with all the JavaScript that is needed to run the page and make it interactive.

If, however, the JavaScript bundle is huge, or you have a slow connection, this process can take a long time and the user will be waiting for the page to become interactive, or to see meaningful content. For optimizing the user experience and avoiding the user having to sit on a blank screen, we can use server rendering.

Server rendering is a technique where you render the HTML output of your React components on the server and send HTML from the server. This lets the user view some UI while JS bundles are loading and before the app becomes interactive. Server rendering further enhances the user experience of loading the page and reducing the time to interact.

Before React 18, this part was often the bottleneck of the app and would increase the time it took to render the component. Now React 18 adds support for Suspense on the server. With the help of suspense, you can wrap a slow part of your app within the Suspense component, telling React to delay the loading of the slow component. This can also be used to specify a loading state that can be shown while it’s loading.

Strict mode

Strict mode in React 18 will simulate mounting, unmounting, and re-mounting the component with a previous state. This sets the ground for a reusable state in the future where React can immediately mount a previous screen by remounting trees using the same component state before unmounting.

Strict mode will ensure components are resilient to the effects of being mounted and unmounted multiple times.

IE11 no longer supported

IE11 is no longer supported since React 18. If your app needs to continue bringing support to IE11, you will need to stay at React 17. x.

Conclusion

Some cool features like Automatic Batching or Adding Suspense should improve the performance of React in the latest release. I’m really excited to see how these new features will perform in a real-life app, but they look more than promising. In a summary, React 18 sets the foundation for future releases and focuses on improving the user experience.

Upgrading to React 18 should be straightforward and your existing code should not break after the update. The upgrade process should not take more than an afternoon.

Tags: