Enhancing Forms with React Server Components

Rate this content
Bookmark
Github

In this talk, we explore the application of React Server Components (RSC) to elevate the functionality and efficiency of forms. We will touch upon the core principles of RSC and their specific benefits for form development, such as improved load times and streamlined server-side processing. Additionally, we’ll learn the latest advancements in React 19 and the introduction of multiple new hooks.Attendees will gain insights into practical strategies for integrating RSC into forms, focusing on enhancing user experience and reducing front-end complexities.

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

FAQ

Aurora notes that while server functions can create endpoints accessible from the client, it's important to handle what data is sent back carefully to avoid security issues.

Aurora enjoys being the first speaker because it allows her to relax and watch others without feeling stressed.

Aurora uses Zod for runtime validation of form data and React 19's use action state for handling client-side interactivity and error states.

Aurora uses React, Prisma as an ORM, a local database, and Tailwind CSS in her project.

Aurora is a web developer from Norway working as a consultant in Oslo.

Aurora's demonstration focuses on working with forms and server components using React.

React 19 allows binding the form action property to a function, enabling server-side functions to be callable from the client.

Aurora is a huge fan of Tailwind CSS.

Server components reduce the JavaScript on the client, minimize front-end complexity, and allow asynchronous data fetching directly within the component.

Aurora mentions Conform and Vest.js as libraries that can optimize forms, providing features like validation and use action state integration.

Aurora Scharff
Aurora Scharff
27 min
13 Dec, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
My name is Aurora, a web developer from Norway, demonstrating a practical example of working with forms and server components using React 19. The server function is created using the `useServer` directive and allows functions to be callable from the client. The form submission and validation are handled server-side using Prisma and a message schema with Zod. The useActionState hook is used for server-side logic and updating the client state. Client-side JavaScript is used for form behavior and preventing form reset. The form is progressively enhanced and can handle multiple submissions with feedback to the user. The talk also emphasizes the reusability of the pending pattern and creating custom client components. Optimistic updates are implemented using the useOptimistic hook. React 19 and server components offer a new option to create robust forms. Using server and client notations in production services should be done with caution due to potential data leakage. Endpoints and server functions should be handled securely. Other libraries like Conform and Vest.js offer options for optimizing forms with React 19.

1. Part 1: Introduction and Setup

Short description:

My name is Aurora. I'm a web developer from Norway. I work as a consultant in Oslo and actively build with React components in my project. I'm excited to demo a practical example of working with forms and server components. The setup uses Prisma as an ORM, a local database, and Tailwind for CSS. All components are server components by default and can be made async. The form is currently non-functional, but we'll enhance it using React 19 to make it interactive while minimizing JS on the client. React 19 was recently released after being in RC for half a year.

My name is Aurora. I'm a web developer from Norway, and I work as a consultant in Oslo, and I'm building actively with React components in my project, and that's where I try to get my knowledge and make some examples to help teach other people about that.

How many people use React server components here? Okay, quite a lot. Wow, that's good, that's good. Nice.

I'm excited to be demoing a practical example of working with forms and server components here today, and I'm going to be coding something that is based on or inspired by a feature that I built in my current project. So let's get right to it.

So the setup here is an XGS app router course, and it's using Prisma as an ORM and a local database and Tailwind for CSS. I'm a huge Tailwind fan. And let's just go through the starting files here.

So since we're in the app router, everything is a server component by default, right? And that means that all of these components here are, wow, okay, are server components by default. And that means that I can actually make them async. So server components can be async, and I can actually asynchronously fetch data right inside the component itself.

And here I have a message box, and it's fetching messages from the database directly through Prisma. And then there is also a message display component here, or I'm mapping the messages to message display components. And here, all we need to do is just style based on whether the message is written by the user. So just a server component, nothing special here.

And there is also a message input, and that's this form here, and it doesn't do anything right now. It's just a form with a single input, and I'll just test it here. So nothing's going to happen.

So this is all server component, which means that there's no JS added to the client bundle for any of these components. And let's enhance this with React 19. The goal will be to make this interactive, while minimizing the JS on the client and reducing the front-end complexity. And let's begin by just making the form work. So I'm going to use React 19's extension of the form element to bind the action property to a function. This is we can do this with React 19 now.

And React 19 was just released like last week, two weeks ago, finally, after being RC for like half a year. So, whoo. Yeah, that's nice. Yeah.

2. Part 2: Creating the Server Function

Short description:

We can bind to a function here. I'm going to create a server function using the directive of React 19, use server. Every function in this file will be callable as server code, but callable from the client. We'll export an async function, submit message, which takes a form data object. Each field in this form will be submitted with its value inside the form data object. We'll use this to insert into the database using Prisma. We also need a created by ID, which can be passed as an additional argument to the server function. We can use dot bind or a hidden input to accomplish this. It's important to note that passing the user ID from the client side is not recommended without proper server-side authentication setup.

Anyway, we can bind to a function here. So I'm going to bind to submit message and I'm going to create a server function. So I'll do it here in my data access layer. I'll just say submit message TS. And since I'm going to make a server function, I will be using the directive of React 19, use server. And what this means is that every function in this file will be callable as server code, but callable from the client. And we'll have a hidden API endpoint generated automatically. So we're going to export an async function here, which is the submit message, if I can spell function. That's a good thing if I can do a function. There we go. And this will take in a form data object of type form data. And what this means is that each field in this form would be submitted with its value inside the form data object. And we can use this to just insert into the database using Prisma, create a message where the data will be content here. I'll just get it from the form data. We'll type it as a string for now. And I also need a created by ID here. And that means that I somehow need to pass an additional argument to this server function. And there's a couple ways we can do this. We can do like a dot bind. That's one way. Or we can use a hidden input. So here I'm going to use a hidden input, bind it to the user ID, and I can just import this server function here. And now I can get this from the form data. There we go. And let's try to wrap this up here. And I have to add a bit of a disclaimer here because you don't really want to pass the user ID from the client side. That's just an example of how you can pass additional parameters when you do encounter that. So you would want some kind of server-side authentication setup. But this is OK for now. So let's try it out.

QnA

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

Case Study: Building Accessible Reusable React Components at GitHub
React Summit 2024React Summit 2024
29 min
Case Study: Building Accessible Reusable React Components at GitHub
Watch video: Case Study: Building Accessible Reusable React Components at GitHub
The talk discusses building accessible React components and emphasizes the importance of using the correct HTML elements and ARIA roles for accessibility. It explains how to navigate and select options within a form and how to add supplementary text using Aria described by. The speaker also discusses the benefits of using conditional checkboxes and ARIA disabled to improve the UI. Additionally, the talk explores the role of JavaScript in web accessibility and provides recommendations for testing website accessibility.
React Server Components in AI Applications
React Advanced 2024React Advanced 2024
17 min
React Server Components in AI Applications
Today we will discuss React server components with AI and how to build a better search experience using them. We will learn how to make a Next.js app AI-enabled using the Vercel AI SDK. The Vercel AI SDK's streamUI function with the GPT 4.0 model will be used to make suggestions interactive. We will explore the use of history and conversation in AI and how to continue the conversation and read the result. The concept of generative UI with the vector database will be introduced, along with querying the database for movies. We will process user queries and return movies based on them. The power of React server components in enhancing UI will be demonstrated. In summary, the Talk covers vector embeddings, natural language search, and generative UI.
Composition vs Configuration: How to Build Flexible, Resilient and Future-proof Components
React Summit 2022React Summit 2022
17 min
Composition vs Configuration: How to Build Flexible, Resilient and Future-proof Components
Top Content
Today's Talk discusses building flexible, resilient, and future-proof React components using composition and configuration approaches. The composition approach allows for flexibility without excessive conditional logic by using multiple components and passing props. The context API can be used for variant styling, allowing for appropriate styling and class specification. Adding variants and icons is made easy by consuming the variant context. The composition and configuration approaches can be combined for the best of both worlds.
The Worlds Most Expensive React Component and How to Stop Writing It
React Advanced 2021React Advanced 2021
23 min
The Worlds Most Expensive React Component and How to Stop Writing It
Top Content
Today's Talk discusses expensive React components and API design, with a focus on the cost of coordination and overcoming imposter syndrome. The speaker shares a story about a cat trying to fix salted coffee, highlighting the importance of finding simple solutions. The billion dollar component on ReactJS.org is examined as an example of an expensive component. Techniques for customizing messages, improving accessibility, and using polymorphic props are discussed. The Talk concludes by emphasizing the cost of communication and the need to evaluate if props and components are the right tools for the job.
Find Out If Your Design System Is Better Than Nothing
React Summit 2022React Summit 2022
20 min
Find Out If Your Design System Is Better Than Nothing
Building a design system without adoption is a waste of time. Grafana UI's adoption is growing consistently over time. The factors affecting design system adoption include the source mix changing, displacement of Homebrew components by Grafana UI, and the limitations of Grafana UI's current state. Measuring adoption is important to determine the success of a design system. The analysis of code through static code analysis tools is valuable in detecting and tracking component usage.
How to achieve layout composition in React
React Summit 2022React Summit 2022
8 min
How to achieve layout composition in React
This talk discusses achieving layout composition in React using Bedrock Layout Primitives. By componentizing CSS layout, complex layouts can be achieved and reused across different components. The talk also covers the challenges of achieving complex layouts, such as card lineups, and provides solutions for maintaining alignment and responsiveness. The BedrockLayout primitive library simplifies web layouts and offers flexibility in composing layouts.

Workshops on related topic

Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
Top Content
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
 
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
 
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
 
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
From Idea to Production: React Development with a Visual Twist
React Summit 2023React Summit 2023
31 min
From Idea to Production: React Development with a Visual Twist
WorkshopFree
Omer Kenet
Omer Kenet
Join us for a 3-hour workshop that dives into the world of creative React development using Codux. Participants will explore how a visually-driven approach can unlock creativity, streamline workflows, and enhance their development velocity. Dive into the features that make Codux a game-changer for React developers. The session will include hands-on exercises that demonstrate the power of real-time rendering, visual code manipulation, and component isolation all in your source code.
Table of the contents: - Download & Setup: Getting Codux Ready for the Workshop- Project Picker: Cloning and Installing a Demo Project- Introduction to Codux Core Concepts and Its UI- Exercise 1: Finding our Feet- Break- Exercise 2: Making Changes While Staying Effective- Exercise 3: Reusability and Edge Case Validation- Summary, Wrap-Up, and Q&A
Crash Course into TypeScript for content from headless CMS
React Summit 2022React Summit 2022
98 min
Crash Course into TypeScript for content from headless CMS
WorkshopFree
Ondrej Polesny
Ondrej Polesny
In this workshop, I’ll first show you how to create a new project in a headless CMS, fill it with data, and use the content in your project. Then, we’ll spend the rest of time in code, we will:- Generate strongly typed models and structure for the fetched content.- Use the content in components- Resolve content from rich text fields into React components- Touch on deployment pipelines and possibilities for discovering content-related issues before hitting production
You will learn:- How to work with content from headless CMS- How content model can be leveraged to generate TS types and what benefits it brings to your project- How not to use string literals for content in code anymore- How to do rich text resolution into React components- How to minimize or avoid content-related issues before hitting production