Next.js for React.js Developers

Rate this content
Bookmark

In this advanced Next.js workshop, we will delve into key concepts and techniques that empower React.js developers to harness the full potential of Next.js. We will explore advanced topics and hands-on practices, equipping you with the skills needed to build high-performance web applications and make informed architectural decisions.


By the end of this workshop, you will be able to:

1. Understand the benefits of React Server Components and their role in building interactive, server-rendered React applications.

2. Differentiate between Edge and Node.js runtime in Next.js and know when to use each based on your project's requirements.

3. Explore advanced Server-Side Rendering (SSR) techniques, including streaming, parallel vs. sequential fetching, and data synchronization.

4. Implement caching strategies for enhanced performance and reduced server load in Next.js applications.

5. Utilize React Actions to handle complex server mutation.

6. Optimize your Next.js applications for SEO, social sharing, and overall performance to improve discoverability and user engagement.

This workshop has been presented at React Day Berlin 2023, check out the latest edition of this React Conference.

FAQ

React Server Components (RSC) are a type of React component that runs exclusively on the server. They aim to reduce client-side code, enhance security, improve latency, and provide a better user and developer experience by not sending extra JavaScript to the client.

Next.js offers several SEO features, including static and dynamic metadata, file-based metadata like robots.txt and sitemaps, and built-in support for improving site speed and structure. These features help improve search engine visibility and user experience.

The benefits of React Server Components include reduced client-side code, enhanced security, improved latency, and a better user and developer experience. They also allow for selective hydration and streaming, which improve performance and user experience.

To use React Server Components with Next.js, simply create a component without the 'use client' directive. Next.js makes React Server Components the default in the latest versions. You can also use server actions and data fetching within these components.

Edge runtimes run closer to the users at the edge of the network, providing low latency and faster response times. Node runtimes run on centralized servers or local machines and are more general-purpose. Each has its specific advantages and limitations, depending on the use case.

Yes, React Server Components can technically be used without Next.js, but it is not advisable for production due to the complex setup required. Next.js provides a streamlined and efficient way to use React Server Components.

Next.js extends the native fetch API to automatically cache fetch requests. You can control caching behavior using options like 'cache: "no-store"' and 'revalidate' to specify when data should be re-fetched. Next.js also supports React Cache and unstable_cache for more advanced caching strategies.

React Server Components run exclusively on the server and never get hydrated on the client side, which means no extra JavaScript is sent to the client. SSR, on the other hand, involves rendering React on the server and then sending HTML to the client, which then hydrates the page and makes it interactive.

To enable Edge runtime for your API routes in Next.js, set 'export const runtime = "edge"' at the top of your API route file. This will ensure that the API route runs on the Edge runtime, providing faster response times.

Server actions in Next.js are asynchronous functions that run on the server. They can be used in both server and client components. When used in client components, Next.js converts these actions into POST requests to the server. This allows for secure and efficient server-side operations within client-side code.

Adrian Hajdin
Adrian Hajdin
157 min
15 Dec, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
The Workshop covers advanced topics related to Next.js and React, including React Server Components and their benefits, using React Server Components with Next.js, caching and data fetching optimization, server actions and execution, and the differences between Edge and Node runtimes in Next.js. The Workshop also explores the use of React suspense for streaming SSR, selective hydration, and error management with server actions. Additionally, the Workshop provides examples, a GitHub repo, a Next.js course, and a community forum for further learning and discussion.

1. Introduction and Workshop Overview

Short description:

Thank you for joining the workshop. We will cover useful and advanced topics related to Next.js and React. Let's get started!

Hello. Thank you all so much for making the time to get in here and for choosing this workshop over maybe some other ones. So I hope you're excited about the topic. We'll try to go over a lot of useful stuff while trying not to keep it too boring or too dull. So I'm going to give my best to just make it somewhat enjoyable, enjoyable to watch and listen to as much as we can as we will be diving into some advanced topics as well.

So I'll give my best. I went ahead and my team as well. I got to give huge props to them for preparing even the slides, the presentation, everything. We're going to have some live demos. We're going to have a lot of stuff. So I'm really grateful for you being here. And while people are joining, we can slowly kind of get started.

So I'm guessing that kind of the goal of all of you here is maybe seeing how we can better leverage not only what Next.js is offering, but what React is offering, and then what Next.js kind of simplifies and creates a wrapper off of, right, to better use the React, but therefore, Next.js code in production as well. That's kind of going to be the topic for today.

2. React Server Components and Next.js

Short description:

React Server Components, the biggest talk of 2023. Questions like what is RSC? Isn't it the same as SSR? Why is React turning back to PHP? How does this fit with Next.js? I'll untangle the mess. I'm Adrian, founder of JavaScript Mastery, recognized as a GitHub star. I'll explain React server components and their connection with Next.js. Pre-React server component era, React guaranteed to run on the client's browser. SSR addressed performance and SEO drawbacks. Hydration process reconciles virtual and static DOM. React server components don't hydrate on the client side, resulting in smaller JavaScript bundles and faster page loading.

So diving right in, React Server Components, probably the biggest talk of 2023 after AI. If you've been on Twitter or X, you've probably been seeing people talking about it every single day. Some people love them. Some people hate them. And most people are just confused. We have questions like, what is RSC, as in React Server Components? Isn't it the same as SSR? Why is React turning back to PHP? How does this all fit with Next.js? And can I use it without Next.js? Right now, that's a bit of a mess. I'll do my best to untangle that mess for you.

So before that, a little self-introduction. I'm Adrian, the founder of JavaScript Mastery. We've posted a lot of different educational YouTube videos on topics such as JavaScript, React, and over the last year, a lot of Next.js. And also, I've been recognized as a GitHub star, kind of position offered by GitHub for people that really try to give back to the audience and to people focusing on education. So I give my best to create over hundreds of project-based videos where we teach developers how to build real applications start to finish. And I've been working with the new Next.js a lot, ever since it came out, almost using it in all of our YouTube videos. We had it a lot, building real applications, teaching it in our Next.js course as well. And it's completely new Next.js. All from 13 to 14 and even further, there's a lot of new stuff happening with Next.js. We also created the Next.js course right here that almost 3,000 people have joined. And in this workshop, I'll explain what I've learned about React server components and how they connect with Next.js in a way that's easy to understand.

So let's begin with a warm-up on pre-React server component era. Things were simple and straightforward. React was guaranteed to run on the client's browser, nothing else. Simply ship big chunks of JavaScript bundles with minimal single HTML file and tell the client's browser to handle everything else. The process, as we know it, the client makes a request to the server, which looks something like this. The server responds to HTML and JavaScript bundle. The client renders HTML and downloads everything mentioned in the JavaScript bundle. The client executes that JavaScript and then paints the content on the screen. This was surprisingly amazing web invention. It still is, but like all things, it still has drawbacks.

Yes, even React has drawbacks, the most important ones being performance. The more JavaScript you ship, the longer it will take for your site to load initially. And in today's world, the first impression is crucial to keep your users engaged on our websites. We also must not forget about the low-end devices, where we presume that all users have top-notch devices, networks, and browsers and trusting that their browser could handle it. Yet, not everyone owns the latest devices, and we can't overlook the fact that over time, we're not incorporating increasingly advanced features into websites. If you've experimented with Next.js during development, you might have observed that it doesn't perform optimally on MacBooks with Intel chips. They're powerful machines, but new technology is demanding. As new technology evolves, so do challenges for users on less advanced setups that were powerful some day. And of course, we can't talk about React's drawbacks without mentioning SEO. Yes, yes, you heard that multiple times, React doesn't play well with SEO. It would have been amazing if web crawlers understood JavaScript, but unfortunately, that's not the case. And with minimal HTML from React, our website doesn't get to properly understand SEO. So, to address this problem, Next.js implemented SSR. SSR, server-side rendering, this method involves rendering React on a server, generating HTML, and then sending it to the client. The client is then responsible for rendering those HTML nodes and elements and incorporating the necessary JavaScript to enable interactive content. It's important to understand that as of now, SSR can only render React components that are suitable for rendering on the server. Components requiring interactivity, such as those with event listeners or dependencies on web APIs, aren't executed by SSR. You can think of SSR as a method to create a blueprint of our website. It generates and displays how your webpage will initially appear.

For example, consider the following scenario on the page. We have a home.js file, or we have a typical counter that you've seen hundreds of times. I believe it was also featured in React.js docs as one of the first examples of using states when hooks came out. How many of you were here for React 15, React 16, when we transitioned from class-based components to just hooks? Feel free to let me know in the chat. Not a lot of new generations of developers that are coding right now have been through that time. Have you been here for that transition? Yeah, it's crazy to think that some of us have started with class components and some of us, or some of you maybe, have never used class-based components, which is a pretty interesting thing to think about. We have this example right here, and the result of the SSR output would be like this, where we simply have welcome to my new Next.js app. Where we have the button and the counter. That's the SSR. An HTML page is produced here, comprising a list of elements and nodes, representing the components of that page. But what about interactivity? All the states and event listeners are dispatched to the client and as JavaScript bundles, which the client browser loads and initiates the construction of the virtual DOM. The client compares the static DOM we received initially with the virtual DOM it will create using the provided JavaScript code, and then determines if they properly match. If not, it will throw an error, saying that many Next.js developers are frustrated about, which is going to look something like this. A hydration error. This entire process of reconciling the virtual DOM, which the client believes represents the page, with the actual static DOM that the server delivered, is called hydration. Everyone's favorite, Dan Abramov, put it in this way, through his mental models. Before, so without the SSR, we have the React tree, where we render components to HTML. We have the main.js and then we bundle the code for interactions like this. And then after SSR, it's going to look something like this. Where we have the server tree, with the file system, databases, internal services, and a lot of other stuff. And we pass props to the React tree, like this. Basically, a virtual DOM, or tree, created by the client, which looks like this. Server, client, and now we have everything happening on the client as well. Yeah, I can see in the messages as well that Davie sent the builder.io React hydration overlay. So, that's a pretty cool thing to note. We can also definitely share it in the Discord, so whenever we have anything, we have a forum and we can keep our discussion there. It's quite useful to know that we can have better and improved error messages when it comes to hydration. Thank you for sharing that. But that's enough about SSR for now. You get it. Since we have this solid SSR approach, why should we bother with React server components? Well, the conventional hydration we discussed earlier, before React server components and Next 13, involved a full page hydration. This meant that when the page loaded, the entire React component 3, including all components, whether initially visible or interacted with by the user, were hydrated on the client side. What does this mean for performance? Although you can see something on the page, it won't be interactive until the client loads everything related to that page, specifically the necessary JavaScript bundle to hydrate the static tree. Sure, we achieve a faster initial load at this stage, but then there's a delay we can interact with, and because we're waiting for the JavaScript to hydrate, there's a gap. For more extensive codebases, it can lead to larger initial page loads and processing of JavaScript, even for components that may not be initially required. So here's where the React server components step in. React server component is a fresh component type. It's assured to run exclusively on the server. They never get hydrated on the client side. So as a result, no extra JavaScript is sent, resulting in a smaller JavaScript bundle size, faster page loading, selective hydration, and an enhanced experience for both UI and developer experience. But before that, let me explain how does React server component work and how we can use them. It's important to note that React server components are exclusively a React feature. There's been a lot of debate on the internet now.

Watch more workshops on topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Concurrent Rendering Adventures in React 18
React Advanced 2021React Advanced 2021
132 min
Concurrent Rendering Adventures in React 18
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Hooks Tips Only the Pros Know
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
Introducing FlashList: Let's build a performant React Native list all together
React Advanced 2022React Advanced 2022
81 min
Introducing FlashList: Let's build a performant React Native list all together
Top Content
Featured Workshop
David Cortés Fulla
Marek Fořt
Talha Naqvi
3 authors
In this workshop you’ll learn why we created FlashList at Shopify and how you can use it in your code today. We will show you how to take a list that is not performant in FlatList and make it performant using FlashList with minimum effort. We will use tools like Flipper, our own benchmarking code, and teach you how the FlashList API can cover more complex use cases and still keep a top-notch performance.You will know:- Quick presentation about what FlashList, why we built, etc.- Migrating from FlatList to FlashList- Teaching how to write a performant list- Utilizing the tools provided by FlashList library (mainly the useBenchmark hook)- Using the Flipper plugins (flame graph, our lists profiler, UI & JS FPS profiler, etc.)- Optimizing performance of FlashList by using more advanced props like `getType`- 5-6 sample tasks where we’ll uncover and fix issues together- Q&A with Shopify team
React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced 2021React Advanced 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced 2022React Advanced 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a web framework built on React Router that focuses on web fundamentals, accessibility, performance, and flexibility. It delivers real HTML and SEO benefits, and allows for automatic updating of meta tags and styles. It provides features like login functionality, session management, and error handling. Remix is a server-rendered framework that can enhance sites with JavaScript but doesn't require it for basic functionality. It aims to create quality HTML-driven documents and is flexible for use with different web technologies and stacks.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced 2023React Advanced 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Using useEffect Effectively
React Advanced 2022React Advanced 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
(Easier) Interactive Data Visualization in React
React Advanced 2021React Advanced 2021
27 min
(Easier) Interactive Data Visualization in React
Top Content
This Talk is about interactive data visualization in React using the Plot library. Plot is a high-level library that simplifies the process of visualizing data by providing key concepts and defaults for layout decisions. It can be integrated with React using hooks like useRef and useEffect. Plot allows for customization and supports features like sorting and adding additional marks. The Talk also discusses accessibility concerns, SSR support, and compares Plot to other libraries like D3 and Vega-Lite.