SlideShare a Scribd company logo
Mastering React Server Components and Server Actions in React 19
Mastering ReactServer
Components andServer
Actions in React 19
Maurice de Beijer
@mauricedb
 Maurice de Beijer
 The Problem Solver
 Freelance developer/instructor
 Currently at https://someday.com/
 Twitter: @mauricedb
 Web: https://www.theproblemsolver.dev/
 E-mail: maurice.de.beijer@gmail.com
3
© ABL - The Problem Solver
Topics
 What are React Server Components and why would you care?
 Using Next.js and the App Router
 Turning a React Client Component into a React Server Component
 Updates and caching with React Server Components
 Querying the database from a React Server Component
 Suspense & React Server Components
 React Server Components and streaming
 Which components are really React Server Components?
 Using React Server Actions
© ABL - The Problem Solver 4
Type it out
by hand?
“Typing it drills it into your brain much better than
simply copying and pasting it.You're forming new
neuron pathways.Those pathways are going to
help you in the future. Help them out now!”
© ABL - The Problem Solver 5
Prerequisites
Install Node & NPM
Install the GitHub repository
© ABL - The Problem Solver 6
Install
Node.js & NPM
© ABL - The Problem Solver 7
Following
Along
 Repo: https://github.com/mauricedb/react-server-components-24
 Slides: https://www.theproblemsolver.dev/docs/react-advanced-
2024.pdf
© ABL - The Problem Solver 8
Create a new
Next.js app
with shadcn/ui
© ABL - The Problem Solver 9
 npx shadcn@latest init --src-dir
The changes
© ABL - The Problem Solver 10
Clone the
GitHub
Repository
© ABL - The Problem Solver 11
Install NPM
Packages
© ABL - The Problem Solver 12
 ☞ Use: npm install –force ☜
Install NPM
Packages
© ABL - The Problem Solver 13
Start branch
© ABL - The Problem Solver 14
 Start with the 00-start branch
 git checkout --track origin/00-start
Start the
application
© ABL - The Problem Solver 15
The
application
© ABL - The Problem Solver 16
What are ReactServer
Components?
© ABL - The Problem Solver 17
ReactServer
Components
 React Server Components (RSC) only execute on the server
 Traditionally React components always execute in the browser
 RSC are not the same as Server Side Rendering
 With SSR components are executed both on the client and server
 Applications are a combination of server and client components
 The result:The back and front-end code are more integrated
 Leading to better type safety ☺
© ABL - The Problem Solver 18
Before RSC
(noSSR)
© ABL - The Problem Solver 19
ServerSide
Rendering
© ABL - The Problem Solver 20
With RSC
© ABL - The Problem Solver 21
ReactServer
Components
© ABL - The Problem Solver 22
 Server components can be asynchronous
 Great to load data from some API
 Server components render just once
 No re-rendering with state changes or event handling
 The server component code is not send to the browser
 Can safely use secure API key’s etc.
 Smaller bundle sizes
ReactServer
Component
© ABL - The Problem Solver 23
ReactClient
Components
© ABL - The Problem Solver 24
 Server components can render both server and client components
 Client components can only render other client components
 Adding 'use client’ to the top of a component makes it a client
component
 Used as a directive for the bundler to include this in the client JS bundle
 A client component is still executed on the server as part of SSR
 When using Next.js
Next.js and the
App Router
© ABL - The Problem Solver 25
Next.js and
theApp
Router
 React is no longer just a client side library
 We need additional server side capabilities
 As well as additional code bundling options
 Next.js is the best production option available
 ☞ Remix doesn’t support RSC yet ☜
 There are also more experimental options
 Waku from Daishi Kato
 React Server Components Demo from the React team
© ABL - The Problem Solver 26
Rendering RSC’s
 React Server Components are only rendered on the server
 And shipped to the client as a JSON like structure
 The React Server Component Payload
 The client then injects these JSON objects into the React tree
 Where it would previously have rendered these components themself
 ☞ React already used a 2 step process ☜
 Components render to a virtual DOM
 Just a series of JavaScript objects
 Reconciliation maps the virtual DOM to the browser DOM
 Or an HTML stream in the case or Server Side Rendering
© ABL - The Problem Solver 27
Async transport  RSC’s are streamed asynchronously to the client
 Enables using Suspense boundaries while loading
© ABL - The Problem Solver 28
Code bundling
 Multiple JavaScript bundles have to be made
 The client and server have different code bundles
 Server Component code is never executed on the client
 Can use react-server-dom-webpack or a similar package
© ABL - The Problem Solver 29
Fetching data in a RSC
© ABL - The Problem Solver 30
Fetching data
in a RSC
 React Server Components an execute normal Node.js code
 Read/write files on disk
 Do fetch requests to other servers
 Execute CRUD in a database
 RSC’s can be asynchronous where needed
 Just await whatever action needs to be done
© ABL - The Problem Solver 31
srcapp
science-fiction
page.tsx
© ABL - The Problem Solver 32
Async server
child components
© ABL - The Problem Solver 33
Child RSC
components
 A RSC component can render other RSC child components
 They can execute the same server based code
 Including async/await where needed
© ABL - The Problem Solver 34
srcappscience-
fictionpage.tsx
© ABL - The Problem Solver 35
srccomponents
movie-card.tsx
© ABL - The Problem Solver 36
Suspense & RSC pages
© ABL - The Problem Solver 37
Suspense &
RSC pages
 React Server Components are suspended until they resolve
 Can be controlled with <Suspense /> boundaries
 Next.js makes it easy to suspend when rendering an async page
 Add a loading.tsx next to the page.tsx
 They can be nested and the closest loading component will be used
© ABL - The Problem Solver 38
srcapp
science-fiction
page.tsx
© ABL - The Problem Solver 39
srcapp
science-fiction
loading.tsx
© ABL - The Problem Solver 40
RSC and streaming
© ABL - The Problem Solver 41
RSC and
streaming
 Async React Server Components are streamed to the browser
 Using the React Server Component Payload
 On the client they are suspended until the component resolves
 Server action responses can also stream components back
 After a revalidatePath() or a revalidateTag()
© ABL - The Problem Solver 42
RSC Payload
© ABL - The Problem Solver 43
Client components
© ABL - The Problem Solver 44
Client
components
 Client components are required in a number of scenarios
 With interactive UI elements like elements with a click handler
 When using browser API’s like localStorage
 When using React hooks like useState(), useEffect() etc.
 Add the `use client` directive
 Makes a component a client component
 Client components render in the browser
 Can’t be asynchronous (for now)
 Can’t access files or databases on the local machine
 Other than using browser API’s
 With Server Side Rendering they can also execute on the server
 Next.js uses SSR by default
© ABL - The Problem Solver 45
ClientComponent
or
ServerComponent
 React Server Components normally perform better
 Only render once on the server
 The code doesn’t need to be shipped to the browser
 Can be async and await data to be fetched
 No need for a render/effect/re-render cycle in the browser
 Components that don’t need client capabilities should be SRC’s
 State, effects, browser API’s etc. are client requirements
© ABL - The Problem Solver 46
srccomponents
favourite-heart.tsx
© ABL - The Problem Solver 47
What does 'use client’
really do
© ABL - The Problem Solver 48
What is a
server
component?
 What is a server component and what is not?
 Client components are marked with 'use client'
 But not all other components are server components
 With a component without 'use client’ it depends on their parents
 If a component is a client component
 Then all components it renders are also client components
 ☞There is no 'use server' for server components ☜
 The 'use server’ directive exists but is used for Server Actions
 But there is a server-only NPM package
© ABL - The Problem Solver 49
server-only
© ABL - The Problem Solver 50
 Import the server-only NPM package
 With components that must run on the server
GrandChild is
both a client
and server
component
© ABL - The Problem Solver 51
Using an RSC
as a child of a
client
component
© ABL - The Problem Solver 52
 A client component can have a server component as a child
 As long as it doesn’t render it
 Render the child server component from another server component
 And pass it as a children prop into the client component
srccomponents
server-or-client
child.tsx
© ABL - The Problem Solver 53
srccomponents
server-or-client
parent.tsx
© ABL - The Problem Solver 54
Break time
© ABL - The Problem Solver 55
CallingServerActions
© ABL - The Problem Solver 56
CallingServer
Actions
 React Server Actions are functions that we can call on the client
 But then execute on the server
 Add the 'use server' annotation
 Can be at the top of a file or a single function
 Not related to server components
 Can be passed as the action of a client side <form />
 The forms data is passed as a FormData parameter
 Even works if JavaScript is disabled ☺
 Can also be called as a normal asynchronous function
 The network request is handled for you
© ABL - The Problem Solver 57
Form actions
© ABL - The Problem Solver 58
Form actions
 A <form> element can take a ‘action’ prop
 Can point to an action function that executes on the client or server
 More flexible that using the onSubmit
 All the <input> from the form is passed as a FormData parameter
 Use hidden inputs to pass additional data
 The server action function works even if JavaScript is disabled
© ABL - The Problem Solver 59
srcappmovie
[id]edit
page.tsx
© ABL - The Problem Solver 60
srccomponents
movie-editor.tsx
© ABL - The Problem Solver 61
Guarding client
components against
server code
© ABL - The Problem Solver 62
server-only
 Components that render in the browser shouldn’t execute server code
 This would usually result in a runtime error
 An immediate compile time error is better
 The server-only package does this
 npm install server-only
 Add import 'server-only’ to any code that should not be imported
 Only needed in the modules that actually execute the Node code
© ABL - The Problem Solver 63
package.json
© ABL - The Problem Solver 64
srclib
prisma.ts
© ABL - The Problem Solver 65
srcapp
science-fiction
page.tsx
© ABL - The Problem Solver 66
The error
© ABL - The Problem Solver 67
The useFormStatus()
hook
© ABL - The Problem Solver 68
useFormStatus
hook
 The useFormStatus() hook gives information about form submition
 The pending status let’s you know if a submit is active
 ☞ Must be in a component that is rendered as child from the <form> ☜
© ABL - The Problem Solver 69
srccomponents
submit-button.tsx
© ABL - The Problem Solver 70
The useActionState()
hook
© ABL - The Problem Solver 71
useActionState
hook
 Updates component state based on the result of a form action
 The state round trips to the action function
 Useful for form validation etc
 ☞ Note: useFormState for now with production React/Next.js! ☜
 Doesn’t expose an isPending status
© ABL - The Problem Solver 72
package.json
© ABL - The Problem Solver 73
srccomponents
movie-editor.tsx
© ABL - The Problem Solver 74
srcserver
actions.ts
© ABL - The Problem Solver 75
Manually calling a
server action
© ABL - The Problem Solver 76
Manually
calling a server
action
 Server actions act as normal asynchronous functions
 Makes the boundary between server and client almost transparent
 Call like a normal async function when needed
 The network call is handled for you
 Return any result you want
 As long as it can be serialized to JSON
 Don’t use throw new Error(‘Some message’)
 ☞ Error messages are hidden in a production build ☜
© ABL - The Problem Solver 77
srccomponents
favourite-heart.tsx
© ABL - The Problem Solver 78
The useOptimistic()
hook
© ABL - The Problem Solver 79
useOptimistic
hook
 Create more responsive user interfaces
 Immediately update the UI with an optimistic state before an
asynchronous action
 Use whatever optimistic state you want
 Automatically updated when the action completes
© ABL - The Problem Solver 80
srccomponents
favourite-heart.tsx
© ABL - The Problem Solver 81
Error handling & retrying
© ABL - The Problem Solver 82
Error handling
& retrying
 An ErrorBoundary will catch errors in React Server Components
 The normal expected React behavior
 Next.js makes it easy to catch errors
 Add a error.tsx next to the page.tsx
 They can be nested and the closest will be used
© ABL - The Problem Solver 83
srcapp
error-handling
error.tsx
© ABL - The Problem Solver 84
Cleaning up the code
© ABL - The Problem Solver 85
Cleaning up the
code
© ABL - The Problem Solver 86
 It’s considered a best practice not to put server logic in the UI
 Server actions typically go into a separate actions.ts
srcappmovie
[id]edit
page.tsx
© ABL - The Problem Solver 87
srcserver
actions.ts
© ABL - The Problem Solver 88
srccomponents
movie-card.tsx
© ABL - The Problem Solver 89
srcapp
science-fiction
page.tsx
© ABL - The Problem Solver 90
Recommendations with
ReactServerComponents
© ABL - The Problem Solver 91
Recommendations
 Start with Shared components
 Can run on the server or client as needed
 Will default to act as Server Components
 Switch to Server only components if needed
 When you need to use server side capabilities
 Only use Client only components when absolutely needed
 Local state or side effects
 Interactivity
 Required browser API’s
 Learn all about the new capabilities of Next.js
 App Router
© ABL - The Problem Solver 92
Conclusion
 React Server Components are a great new addition to React
 Helps with keeping the client more responsive
 Makes the application architecture easier
 Use Next.js and the App Router
 Because you need a server
 React Client Components
 Are components with state and interactivity and require ‘use client’
 React Server Components are streamed
 And use Suspense boundaries until they are done
 Server Actions are a great way to call back into the server
 They also update the invalidated server components on the client
© ABL - The Problem Solver 93
Thankyouforjoining
© ABL - The Problem Solver 94
Share your thoughts

More Related Content

PDF
React loadable
George Bukhanov
 
PPTX
Better React state management with Redux
Maurice De Beijer [MVP]
 
PPTX
The productive developer guide to React
Maurice De Beijer [MVP]
 
PPTX
The new React
Maurice De Beijer [MVP]
 
PPTX
Client vs Server Components in Next.js.pptx
UdithaKasun3
 
PPTX
Full-stack App in half a Day: Next.js 15 Development Bootcamp
Maurice De Beijer [MVP]
 
PPTX
Web Performance & Latest in React
Talentica Software
 
PDF
Revolutionizing Web Development with React Server Components: A Comprehensive...
Inexture Solutions
 
React loadable
George Bukhanov
 
Better React state management with Redux
Maurice De Beijer [MVP]
 
The productive developer guide to React
Maurice De Beijer [MVP]
 
The new React
Maurice De Beijer [MVP]
 
Client vs Server Components in Next.js.pptx
UdithaKasun3
 
Full-stack App in half a Day: Next.js 15 Development Bootcamp
Maurice De Beijer [MVP]
 
Web Performance & Latest in React
Talentica Software
 
Revolutionizing Web Development with React Server Components: A Comprehensive...
Inexture Solutions
 

Similar to Mastering React Server Components and Server Actions in React 19 (20)

PDF
What is Server-side Rendering? How to Render Your React App on the Server-sid...
Shelly Megan
 
PPTX
Deployment of DevOps Environment with CA Solutions
Nic Swart
 
PPTX
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
zmulani8
 
PDF
Isomorphic React Applications: Performance And Scalability
Denis Izmaylov
 
PDF
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
PDF
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
PPTX
Modernizing Web Apps with .NET 6.pptx
Ed Charbeneau
 
PPTX
Modernizing Web Apps with .NET 6.pptx
Ed Charbeneau
 
PPTX
React gsg presentation with ryan jung &amp; elias malik
Lama K Banna
 
PPTX
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
PDF
React Server Component in Next.js by Hanief Utama
Hanief Utama
 
PPTX
React suspense, not just for Alfred Hitchcock
Maurice De Beijer [MVP]
 
PDF
Top 5 React Performance Optimization Techniques in 2023
ultroNeous Technologies | Best Web App Development Company
 
PDF
Production Experience: Some Insights from Using Vercel and Next.js for Over 3...
KosukeMatano1
 
PPTX
React JS .NET
Jennifer Estrada
 
PDF
React on rails v4
Justin Gordon
 
PDF
NEXT.JS
Binumon Joseph
 
PDF
next-230524050805-d1e22a49.pdferewrewrewrewr
zmulani8
 
PDF
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
What is Server-side Rendering? How to Render Your React App on the Server-sid...
Shelly Megan
 
Deployment of DevOps Environment with CA Solutions
Nic Swart
 
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
zmulani8
 
Isomorphic React Applications: Performance And Scalability
Denis Izmaylov
 
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
Modernizing Web Apps with .NET 6.pptx
Ed Charbeneau
 
Modernizing Web Apps with .NET 6.pptx
Ed Charbeneau
 
React gsg presentation with ryan jung &amp; elias malik
Lama K Banna
 
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
React Server Component in Next.js by Hanief Utama
Hanief Utama
 
React suspense, not just for Alfred Hitchcock
Maurice De Beijer [MVP]
 
Top 5 React Performance Optimization Techniques in 2023
ultroNeous Technologies | Best Web App Development Company
 
Production Experience: Some Insights from Using Vercel and Next.js for Over 3...
KosukeMatano1
 
React JS .NET
Jennifer Estrada
 
React on rails v4
Justin Gordon
 
next-230524050805-d1e22a49.pdferewrewrewrewr
zmulani8
 
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
Ad

More from Maurice De Beijer [MVP] (20)

PPTX
Production-ready Next.js App with Cursor AI
Maurice De Beijer [MVP]
 
PPTX
Building Robust Web Applications with Test-Driven Development and Playwright:...
Maurice De Beijer [MVP]
 
PPTX
Practice TypeScript Techniques Building React Server Components App
Maurice De Beijer [MVP]
 
PPTX
A foolproof Way to Estimate a Software Project
Maurice De Beijer [MVP]
 
PPTX
Surati Tech Talks 2022 / Build reliable Svelte applications using Cypress
Maurice De Beijer [MVP]
 
PPTX
Build reliable Svelte applications using Cypress
Maurice De Beijer [MVP]
 
PPTX
Building Reliable Applications Using React, .NET & Azure
Maurice De Beijer [MVP]
 
PPTX
Concurrent Rendering Adventures in React 18
Maurice De Beijer [MVP]
 
PPTX
Building reliable applications with React, C#, and Azure
Maurice De Beijer [MVP]
 
PPTX
Building large and scalable mission critical applications with React
Maurice De Beijer [MVP]
 
PPTX
Building Reliable Applications Using React, .NET & Azure
Maurice De Beijer [MVP]
 
PPTX
Why I am hooked on the future of React
Maurice De Beijer [MVP]
 
PPTX
Building reliable web applications using Cypress
Maurice De Beijer [MVP]
 
PPTX
Getting started with React Suspense and concurrent rendering
Maurice De Beijer [MVP]
 
PPTX
From zero to hero with the Reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
PPTX
Why I am hooked on the future of React
Maurice De Beijer [MVP]
 
PPTX
From zero to hero with the reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
PPTX
Why I am hooked on the future of React
Maurice De Beijer [MVP]
 
PPTX
I am hooked on React
Maurice De Beijer [MVP]
 
PPTX
Create flexible React applications using GraphQL apis
Maurice De Beijer [MVP]
 
Production-ready Next.js App with Cursor AI
Maurice De Beijer [MVP]
 
Building Robust Web Applications with Test-Driven Development and Playwright:...
Maurice De Beijer [MVP]
 
Practice TypeScript Techniques Building React Server Components App
Maurice De Beijer [MVP]
 
A foolproof Way to Estimate a Software Project
Maurice De Beijer [MVP]
 
Surati Tech Talks 2022 / Build reliable Svelte applications using Cypress
Maurice De Beijer [MVP]
 
Build reliable Svelte applications using Cypress
Maurice De Beijer [MVP]
 
Building Reliable Applications Using React, .NET & Azure
Maurice De Beijer [MVP]
 
Concurrent Rendering Adventures in React 18
Maurice De Beijer [MVP]
 
Building reliable applications with React, C#, and Azure
Maurice De Beijer [MVP]
 
Building large and scalable mission critical applications with React
Maurice De Beijer [MVP]
 
Building Reliable Applications Using React, .NET & Azure
Maurice De Beijer [MVP]
 
Why I am hooked on the future of React
Maurice De Beijer [MVP]
 
Building reliable web applications using Cypress
Maurice De Beijer [MVP]
 
Getting started with React Suspense and concurrent rendering
Maurice De Beijer [MVP]
 
From zero to hero with the Reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
Why I am hooked on the future of React
Maurice De Beijer [MVP]
 
From zero to hero with the reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
Why I am hooked on the future of React
Maurice De Beijer [MVP]
 
I am hooked on React
Maurice De Beijer [MVP]
 
Create flexible React applications using GraphQL apis
Maurice De Beijer [MVP]
 
Ad

Recently uploaded (20)

PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 

Mastering React Server Components and Server Actions in React 19

  • 2. Mastering ReactServer Components andServer Actions in React 19 Maurice de Beijer @mauricedb
  • 3.  Maurice de Beijer  The Problem Solver  Freelance developer/instructor  Currently at https://someday.com/  Twitter: @mauricedb  Web: https://www.theproblemsolver.dev/  E-mail: [email protected] 3 © ABL - The Problem Solver
  • 4. Topics  What are React Server Components and why would you care?  Using Next.js and the App Router  Turning a React Client Component into a React Server Component  Updates and caching with React Server Components  Querying the database from a React Server Component  Suspense & React Server Components  React Server Components and streaming  Which components are really React Server Components?  Using React Server Actions © ABL - The Problem Solver 4
  • 5. Type it out by hand? “Typing it drills it into your brain much better than simply copying and pasting it.You're forming new neuron pathways.Those pathways are going to help you in the future. Help them out now!” © ABL - The Problem Solver 5
  • 6. Prerequisites Install Node & NPM Install the GitHub repository © ABL - The Problem Solver 6
  • 7. Install Node.js & NPM © ABL - The Problem Solver 7
  • 8. Following Along  Repo: https://github.com/mauricedb/react-server-components-24  Slides: https://www.theproblemsolver.dev/docs/react-advanced- 2024.pdf © ABL - The Problem Solver 8
  • 9. Create a new Next.js app with shadcn/ui © ABL - The Problem Solver 9  npx shadcn@latest init --src-dir
  • 10. The changes © ABL - The Problem Solver 10
  • 11. Clone the GitHub Repository © ABL - The Problem Solver 11
  • 12. Install NPM Packages © ABL - The Problem Solver 12  ☞ Use: npm install –force ☜
  • 13. Install NPM Packages © ABL - The Problem Solver 13
  • 14. Start branch © ABL - The Problem Solver 14  Start with the 00-start branch  git checkout --track origin/00-start
  • 15. Start the application © ABL - The Problem Solver 15
  • 16. The application © ABL - The Problem Solver 16
  • 17. What are ReactServer Components? © ABL - The Problem Solver 17
  • 18. ReactServer Components  React Server Components (RSC) only execute on the server  Traditionally React components always execute in the browser  RSC are not the same as Server Side Rendering  With SSR components are executed both on the client and server  Applications are a combination of server and client components  The result:The back and front-end code are more integrated  Leading to better type safety ☺ © ABL - The Problem Solver 18
  • 19. Before RSC (noSSR) © ABL - The Problem Solver 19
  • 20. ServerSide Rendering © ABL - The Problem Solver 20
  • 21. With RSC © ABL - The Problem Solver 21
  • 22. ReactServer Components © ABL - The Problem Solver 22  Server components can be asynchronous  Great to load data from some API  Server components render just once  No re-rendering with state changes or event handling  The server component code is not send to the browser  Can safely use secure API key’s etc.  Smaller bundle sizes
  • 23. ReactServer Component © ABL - The Problem Solver 23
  • 24. ReactClient Components © ABL - The Problem Solver 24  Server components can render both server and client components  Client components can only render other client components  Adding 'use client’ to the top of a component makes it a client component  Used as a directive for the bundler to include this in the client JS bundle  A client component is still executed on the server as part of SSR  When using Next.js
  • 25. Next.js and the App Router © ABL - The Problem Solver 25
  • 26. Next.js and theApp Router  React is no longer just a client side library  We need additional server side capabilities  As well as additional code bundling options  Next.js is the best production option available  ☞ Remix doesn’t support RSC yet ☜  There are also more experimental options  Waku from Daishi Kato  React Server Components Demo from the React team © ABL - The Problem Solver 26
  • 27. Rendering RSC’s  React Server Components are only rendered on the server  And shipped to the client as a JSON like structure  The React Server Component Payload  The client then injects these JSON objects into the React tree  Where it would previously have rendered these components themself  ☞ React already used a 2 step process ☜  Components render to a virtual DOM  Just a series of JavaScript objects  Reconciliation maps the virtual DOM to the browser DOM  Or an HTML stream in the case or Server Side Rendering © ABL - The Problem Solver 27
  • 28. Async transport  RSC’s are streamed asynchronously to the client  Enables using Suspense boundaries while loading © ABL - The Problem Solver 28
  • 29. Code bundling  Multiple JavaScript bundles have to be made  The client and server have different code bundles  Server Component code is never executed on the client  Can use react-server-dom-webpack or a similar package © ABL - The Problem Solver 29
  • 30. Fetching data in a RSC © ABL - The Problem Solver 30
  • 31. Fetching data in a RSC  React Server Components an execute normal Node.js code  Read/write files on disk  Do fetch requests to other servers  Execute CRUD in a database  RSC’s can be asynchronous where needed  Just await whatever action needs to be done © ABL - The Problem Solver 31
  • 33. Async server child components © ABL - The Problem Solver 33
  • 34. Child RSC components  A RSC component can render other RSC child components  They can execute the same server based code  Including async/await where needed © ABL - The Problem Solver 34
  • 36. srccomponents movie-card.tsx © ABL - The Problem Solver 36
  • 37. Suspense & RSC pages © ABL - The Problem Solver 37
  • 38. Suspense & RSC pages  React Server Components are suspended until they resolve  Can be controlled with <Suspense /> boundaries  Next.js makes it easy to suspend when rendering an async page  Add a loading.tsx next to the page.tsx  They can be nested and the closest loading component will be used © ABL - The Problem Solver 38
  • 41. RSC and streaming © ABL - The Problem Solver 41
  • 42. RSC and streaming  Async React Server Components are streamed to the browser  Using the React Server Component Payload  On the client they are suspended until the component resolves  Server action responses can also stream components back  After a revalidatePath() or a revalidateTag() © ABL - The Problem Solver 42
  • 43. RSC Payload © ABL - The Problem Solver 43
  • 44. Client components © ABL - The Problem Solver 44
  • 45. Client components  Client components are required in a number of scenarios  With interactive UI elements like elements with a click handler  When using browser API’s like localStorage  When using React hooks like useState(), useEffect() etc.  Add the `use client` directive  Makes a component a client component  Client components render in the browser  Can’t be asynchronous (for now)  Can’t access files or databases on the local machine  Other than using browser API’s  With Server Side Rendering they can also execute on the server  Next.js uses SSR by default © ABL - The Problem Solver 45
  • 46. ClientComponent or ServerComponent  React Server Components normally perform better  Only render once on the server  The code doesn’t need to be shipped to the browser  Can be async and await data to be fetched  No need for a render/effect/re-render cycle in the browser  Components that don’t need client capabilities should be SRC’s  State, effects, browser API’s etc. are client requirements © ABL - The Problem Solver 46
  • 48. What does 'use client’ really do © ABL - The Problem Solver 48
  • 49. What is a server component?  What is a server component and what is not?  Client components are marked with 'use client'  But not all other components are server components  With a component without 'use client’ it depends on their parents  If a component is a client component  Then all components it renders are also client components  ☞There is no 'use server' for server components ☜  The 'use server’ directive exists but is used for Server Actions  But there is a server-only NPM package © ABL - The Problem Solver 49
  • 50. server-only © ABL - The Problem Solver 50  Import the server-only NPM package  With components that must run on the server
  • 51. GrandChild is both a client and server component © ABL - The Problem Solver 51
  • 52. Using an RSC as a child of a client component © ABL - The Problem Solver 52  A client component can have a server component as a child  As long as it doesn’t render it  Render the child server component from another server component  And pass it as a children prop into the client component
  • 55. Break time © ABL - The Problem Solver 55
  • 56. CallingServerActions © ABL - The Problem Solver 56
  • 57. CallingServer Actions  React Server Actions are functions that we can call on the client  But then execute on the server  Add the 'use server' annotation  Can be at the top of a file or a single function  Not related to server components  Can be passed as the action of a client side <form />  The forms data is passed as a FormData parameter  Even works if JavaScript is disabled ☺  Can also be called as a normal asynchronous function  The network request is handled for you © ABL - The Problem Solver 57
  • 58. Form actions © ABL - The Problem Solver 58
  • 59. Form actions  A <form> element can take a ‘action’ prop  Can point to an action function that executes on the client or server  More flexible that using the onSubmit  All the <input> from the form is passed as a FormData parameter  Use hidden inputs to pass additional data  The server action function works even if JavaScript is disabled © ABL - The Problem Solver 59
  • 60. srcappmovie [id]edit page.tsx © ABL - The Problem Solver 60
  • 62. Guarding client components against server code © ABL - The Problem Solver 62
  • 63. server-only  Components that render in the browser shouldn’t execute server code  This would usually result in a runtime error  An immediate compile time error is better  The server-only package does this  npm install server-only  Add import 'server-only’ to any code that should not be imported  Only needed in the modules that actually execute the Node code © ABL - The Problem Solver 63
  • 64. package.json © ABL - The Problem Solver 64
  • 65. srclib prisma.ts © ABL - The Problem Solver 65
  • 67. The error © ABL - The Problem Solver 67
  • 68. The useFormStatus() hook © ABL - The Problem Solver 68
  • 69. useFormStatus hook  The useFormStatus() hook gives information about form submition  The pending status let’s you know if a submit is active  ☞ Must be in a component that is rendered as child from the <form> ☜ © ABL - The Problem Solver 69
  • 71. The useActionState() hook © ABL - The Problem Solver 71
  • 72. useActionState hook  Updates component state based on the result of a form action  The state round trips to the action function  Useful for form validation etc  ☞ Note: useFormState for now with production React/Next.js! ☜  Doesn’t expose an isPending status © ABL - The Problem Solver 72
  • 73. package.json © ABL - The Problem Solver 73
  • 75. srcserver actions.ts © ABL - The Problem Solver 75
  • 76. Manually calling a server action © ABL - The Problem Solver 76
  • 77. Manually calling a server action  Server actions act as normal asynchronous functions  Makes the boundary between server and client almost transparent  Call like a normal async function when needed  The network call is handled for you  Return any result you want  As long as it can be serialized to JSON  Don’t use throw new Error(‘Some message’)  ☞ Error messages are hidden in a production build ☜ © ABL - The Problem Solver 77
  • 79. The useOptimistic() hook © ABL - The Problem Solver 79
  • 80. useOptimistic hook  Create more responsive user interfaces  Immediately update the UI with an optimistic state before an asynchronous action  Use whatever optimistic state you want  Automatically updated when the action completes © ABL - The Problem Solver 80
  • 82. Error handling & retrying © ABL - The Problem Solver 82
  • 83. Error handling & retrying  An ErrorBoundary will catch errors in React Server Components  The normal expected React behavior  Next.js makes it easy to catch errors  Add a error.tsx next to the page.tsx  They can be nested and the closest will be used © ABL - The Problem Solver 83
  • 85. Cleaning up the code © ABL - The Problem Solver 85
  • 86. Cleaning up the code © ABL - The Problem Solver 86  It’s considered a best practice not to put server logic in the UI  Server actions typically go into a separate actions.ts
  • 87. srcappmovie [id]edit page.tsx © ABL - The Problem Solver 87
  • 88. srcserver actions.ts © ABL - The Problem Solver 88
  • 89. srccomponents movie-card.tsx © ABL - The Problem Solver 89
  • 92. Recommendations  Start with Shared components  Can run on the server or client as needed  Will default to act as Server Components  Switch to Server only components if needed  When you need to use server side capabilities  Only use Client only components when absolutely needed  Local state or side effects  Interactivity  Required browser API’s  Learn all about the new capabilities of Next.js  App Router © ABL - The Problem Solver 92
  • 93. Conclusion  React Server Components are a great new addition to React  Helps with keeping the client more responsive  Makes the application architecture easier  Use Next.js and the App Router  Because you need a server  React Client Components  Are components with state and interactivity and require ‘use client’  React Server Components are streamed  And use Suspense boundaries until they are done  Server Actions are a great way to call back into the server  They also update the invalidated server components on the client © ABL - The Problem Solver 93
  • 94. Thankyouforjoining © ABL - The Problem Solver 94 Share your thoughts