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

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

PDF
NextJS - Online Summit for Frontend Developers September 2020
Milad Heydari
 
PPTX
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
zmulani8
 
PDF
FRONTEND DEVELOPMENT WITH REACT.JS
IRJET Journal
 
PPTX
The productive developer guide to React
Maurice De Beijer [MVP]
 
PDF
Tech Talk on ReactJS
Atlogys Technical Consulting
 
PDF
Universal React apps in Next.js
🐕 Łukasz Ostrowski
 
PDF
What is Server-side Rendering? How to Render Your React App on the Server-sid...
Shelly Megan
 
PPTX
Progressive Web Apps and React
Mike Melusky
 
PPTX
Full Stack_Reac web Development and Application
Jeyarajs7
 
PDF
Server Side React for WordPress by Muhammad Muhsin @ The JavaScript for WordP...
rtCamp
 
PPTX
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
PDF
Server side rendering with React and Symfony
Ignacio Martín
 
PPTX
React workshop
Imran Sayed
 
PDF
Ultimate Guide to React.js Development for Modern Web Projects
BhavikaChauhan14
 
PDF
An Ultimate Guide on React.js Development for Your Next Project
BhavikaChauhan14
 
PPTX
[Final] ReactJS presentation
洪 鹏发
 
PPTX
React Workshop: Core concepts of react
Imran Sayed
 
PPTX
Practice TypeScript Techniques Building React Server Components App
Maurice De Beijer [MVP]
 
PPTX
Ultimate Guide to React.js Development for Modern Web Projects
BhavikaChauhan14
 
PPTX
Introduction to React.js and Next.js.pptx
alpeshconnect1
 
NextJS - Online Summit for Frontend Developers September 2020
Milad Heydari
 
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
zmulani8
 
FRONTEND DEVELOPMENT WITH REACT.JS
IRJET Journal
 
The productive developer guide to React
Maurice De Beijer [MVP]
 
Tech Talk on ReactJS
Atlogys Technical Consulting
 
Universal React apps in Next.js
🐕 Łukasz Ostrowski
 
What is Server-side Rendering? How to Render Your React App on the Server-sid...
Shelly Megan
 
Progressive Web Apps and React
Mike Melusky
 
Full Stack_Reac web Development and Application
Jeyarajs7
 
Server Side React for WordPress by Muhammad Muhsin @ The JavaScript for WordP...
rtCamp
 
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Server side rendering with React and Symfony
Ignacio Martín
 
React workshop
Imran Sayed
 
Ultimate Guide to React.js Development for Modern Web Projects
BhavikaChauhan14
 
An Ultimate Guide on React.js Development for Your Next Project
BhavikaChauhan14
 
[Final] ReactJS presentation
洪 鹏发
 
React Workshop: Core concepts of react
Imran Sayed
 
Practice TypeScript Techniques Building React Server Components App
Maurice De Beijer [MVP]
 
Ultimate Guide to React.js Development for Modern Web Projects
BhavikaChauhan14
 
Introduction to React.js and Next.js.pptx
alpeshconnect1
 

More from Maurice De Beijer [MVP] (20)

PPTX
Full-stack App in half a Day: Next.js 15 Development Bootcamp
Maurice De Beijer [MVP]
 
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
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
React suspense, not just for Alfred Hitchcock
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
The new 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]
 
Full-stack App in half a Day: Next.js 15 Development Bootcamp
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]
 
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]
 
React suspense, not just for Alfred Hitchcock
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]
 
The new 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]
 
Ad

Recently uploaded (20)

PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Ad

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