React Server Functions

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional NextJS Lessons

1.Course Intro
free
⏱️ 2:05
2.Get Setup
free
⏱️ 2:05
3.Project Template
free
⏱️ 5:45
4.Introducing FullStack React
free
⏱️ 4:57
5.App Router Reference
free
⏱️ 7:08
6.NextJS Server vs. "use client" Rendering
⏱️ 5:01
7.Nesting Server and Client Components
⏱️ 8:51
8.Client Only Components
⏱️ 3:48
9.Global CSS in NextJS
⏱️ 6:30
10.CSS Modules and SASS
⏱️ 4:15
11.Tailwind CSS
⏱️ 5:17
12.NextJS Custom Fonts
⏱️ 4:08
13.Static vs Dynamic Rendering
⏱️ 4:55
14.NextJS Link Component
⏱️ 3:20
15.NextJS Link Prefetching
⏱️ 5:49
16.Navigation Scroll with Link
⏱️ 2:02
17.Replace Navigation History
⏱️ 1:35
18.NextJS Image Component
⏱️ 7:01
19.Dynamic Image URLs
⏱️ 5:34
20.Safe Colocation with Private Folders
⏱️ 2:12
21.NextJS Route Groups
⏱️ 3:07
22.Dynamic Routes
⏱️ 5:37
23.NextJS API Routes
⏱️ 6:03
24.NextRequest and NextResponse
⏱️ 2:41
25.Cookies in API Handlers
⏱️ 4:25
26.React Suspense Simplified
⏱️ 2:23
27.Power of Suspense Boundaries
⏱️ 3:52
28.use Promises
⏱️ 3:24
29.Stream Promise Results from Server to Client
⏱️ 3:03
30.use Requires a Cached Promise
free
⏱️ 2:30
31.Suspense Error Boundaries
⏱️ 4:42
32.React Server Functions
⏱️ 4:50
33.Server Actions for Powerful Forms
⏱️ 5:35
34.useActionState to Simplify Form Actions
⏱️ 6:38
35.React Serializable Types
⏱️ 2:42
36.Create Dynamic Images with NextJS ImageResponse
⏱️ 5:54
37.Deploy NextJS Application to Production
⏱️ 3:51
38.NextJS Environment Variables Masterclass
⏱️ 3:50
39.Deploying and Managing Environment Variables
⏱️ 4:38
40.Using Databases for Dynamic Server Side State
free
⏱️ 7:34
41.Mastering NextJS Layout Files
⏱️ 4:54
42.Client State Management with NextJS
⏱️ 3:48
43.Client State Management In Action
⏱️ 8:04
44.Using Client State Management Libraries
⏱️ 5:25
45.Detecting Server vs Client Runtime and useEffect
⏱️ 4:33
46.Demystifying ISR vs SSR vs SSG
⏱️ 3:07
47.Static Site Generation or SSG with NextJS
⏱️ 3:16
48.Incremental Static Regeneration (ISR) Simplified
⏱️ 2:51
49.API Routes Caching with NextJS
⏱️ 3:05
50.Reference Guide to Caching for Modern NextJS
⏱️ 2:47
🚨 Work In Progress 🚧
Subscribe for Launch

React Server Functions

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Why?

A truly game changing feature offered by modern react is the ability to create server functions. At its core, server functions allows client components to call async functions executed on the server.

Core Concept

Traditionally if you want to run some code on the server based on a user action you would expose an HTTP API, but with server functions invoking server code from the client browser as simple as calling a javascript function.

This is demonstrated below where we can invoke functions exported by the server in the context of a 'use server' directive. These functions are called from the client (within the context of a 'use client' directive).

lib/functions.ts
lib/Likes.tsx
app/page.tsx
"use server";

import { getDb } from "./db";

export async function getLikes() {
const db = await getDb();
return db.data.likes;
}
export async function incrementLikes() {
const db = await getDb();
db.data.likes++;
await db.write();
return db.data.likes;
}
export async function resetLikes() {
const db = await getDb();
db.data.likes = 0;
await db.write();
return db.data.likes;
}

Inline Definition

You can even define server function inline anywhere in your server code and pass it as a prop to your client components.

This is demonstrated below where we create a function inline within a server component and pass it as a prop to a client component.

app/page.tsx
lib/Likes.tsx
import { getDb } from "@/lib/db";
import { getLikes } from "@/lib/functions";
import { Likes } from "@/lib/Likes";

export default async function Page() {
const initial = await getLikes();

const decrementLikes = async () => {
"use server";
const db = await getDb();
db.data.likes--;
await db.write();
return db.data.likes;
};

return (
<div>
<h1>Likes</h1>
<Likes initial={initial} decrementLikes={decrementLikes} />
</div>
);
}

Show Pending

You can observe the pending state of a server function call with the useTransition hook that we have also previously covered in our React Course.

This is demonstrated below where we call the server function from the startTransition callback and then use the isPending boolean to customize the user interface.

lib/Likes.tsx
"use client";

import { useState } from "react";
import { incrementLikes } from "./functions";
import { useTransition } from "react";

export function Likes({ initial }: { initial: number }) {
const [likeCount, setLikeCount] = useState(initial);
const [isPending, startTransition] = useTransition();

const onClickUp = () => {
startTransition(async () => {
setLikeCount(await incrementLikes());
});
};

return (
<>
<p>Total Likes: {likeCount}</p>
<button onClick={onClickUp} disabled={isPending}>
{isPending ? "⏳" : "👍"}
</button>
</>
);
}
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

A truly game changing feature offered by modern React is the ability to create server functions, error score server functions. Allow client components to call async functions executed on the server. Traditionally, if you want to run some code on the server based on a user action, you would need to expose an H-T-P-A-P-I, but with server functions, invoking server code from the client browser is as simple as calling a JavaScript function. To create server functions, they need to be within the context of a use server directive. One way to use this directive is to add it to the top of your module.

00:31

As we have done in this example, within this file, we can bring in any server code that we want. For example, here we are bringing in a utility to get the database. Any functions we export within the context of use server will become server functions. For example, the get Likes utility is something that we can invoke from the client. The increment likes utility is something that we can invoke from the client and similarly, the reset likes function is something that we can invoke from the client. A key requirement for server functions is that they must be Asing functions, which is true for all of these utilities. Within our React application, we start off at the server page

01:04

and make that initial call to get the current likes. Next, we render out a simple UI that has a simple heading followed by the likes component, which is going to be a client component. The likes component is going to be a client component because we need to handle clicks and for this purpose, we start off this file with a used client directive. We will maintain the currently displayed state using the used state hook provided by React, and then we bring in our server functions into this client site code with this simple import. Within this component, we accept the initial value which we fetched on the server and we use that to initialize the state variable.

01:38

We create a utility handler for the thumbs up button, and within that we can seamlessly call the server function. This increment likes function updates account within the database and then returns the updated count, which we store within the state. We create another click handler for the reset button within which we invoke the server Reset likes function and once more we update the state with the returned count. Finally, we render out the UI that displays the current like count, has a button wired to on click up, and then has another button with on click wired to on click reset. Notice how easy it was for us

02:10

to call server functions from our client side code and even get back the results returned from the server. Let's take a look at this application in action within the browser. As you would expect, it displays the initial count. We can increment it with a thumbs up and we can even reset it with the reset button. It is important to note that under the hood React is still making STTP calls in order to invoke the server functions, and we can verify that by opening up the network panel. As you make the different function calls, you can see fetch network calls being made by React, but all of the fetch calls the serialization

02:42

and de serialization is handled for us, we simply had to invoke a function. You can even define server functions in line anywhere in your server code and pass it as a prop to your client components. As a demonstration, let's create another utility function within our page server component. Since the module Itself is not within the context of a use server directive, we provide that directive as the first line within the function body. With this server function created, we can pass it as a prop to our client component. Now let's modify our component to accept this new prop, we add the decrement likes prop to the function definition,

03:15

and it is simply going to be a function that returns a promise of a number. We can use this function just like any of the other server functions. For example, within an on click down utility, we invoke decrement likes, await the result and update our state. Finally, we render a new button with its on click wide to this utility. In terms of behavior, this inline function is going to behave the same as a module function and we can verify that within the browser. In addition to thumbs up, we can now thumbs down. You can observe the pending state of a server function call with a use transition hook that we have also previously covered in our React course.

03:49

We've simplified our UI to only show the thumbs up option. We start off by bringing the use transition hook from React. We invoke this within our client component and it returns a couple of two items. One is an is spending state, which will turn true when we are within the context of a start transition callback within our click handler. Instead of invoking the server function directly, we make the call within a start transition callback while the asy callback to start transition is still executing the is spending bullion variable will turn to true. We can use this to render out something custom within the ui.

04:20

For example, we can disable the clicker button and even modify the emoji to be an R glass instead of a thumbs up. This is just one application of the used transition hook. Of course, you can create multiple instances and slice and dice the UI however you want. Now let's verify if the pending state is shown to the user within the browser. When we click the thumbs up button, the transition starts, the is pending turns to two. The button is disabled and the icon is changed, and once it completes, the count is incremented and the button returns to thumbs up.

Professional NextJS

Professional NextJS

1.Course Intro
free
⏱️ 2:05
2.Get Setup
free
⏱️ 2:05
3.Project Template
free
⏱️ 5:45
4.Introducing FullStack React
free
⏱️ 4:57
5.App Router Reference
free
⏱️ 7:08
6.NextJS Server vs. "use client" Rendering
⏱️ 5:01
7.Nesting Server and Client Components
⏱️ 8:51
8.Client Only Components
⏱️ 3:48
9.Global CSS in NextJS
⏱️ 6:30
10.CSS Modules and SASS
⏱️ 4:15
11.Tailwind CSS
⏱️ 5:17
12.NextJS Custom Fonts
⏱️ 4:08
13.Static vs Dynamic Rendering
⏱️ 4:55
14.NextJS Link Component
⏱️ 3:20
15.NextJS Link Prefetching
⏱️ 5:49
16.Navigation Scroll with Link
⏱️ 2:02
17.Replace Navigation History
⏱️ 1:35
18.NextJS Image Component
⏱️ 7:01
19.Dynamic Image URLs
⏱️ 5:34
20.Safe Colocation with Private Folders
⏱️ 2:12
21.NextJS Route Groups
⏱️ 3:07
22.Dynamic Routes
⏱️ 5:37
23.NextJS API Routes
⏱️ 6:03
24.NextRequest and NextResponse
⏱️ 2:41
25.Cookies in API Handlers
⏱️ 4:25
26.React Suspense Simplified
⏱️ 2:23
27.Power of Suspense Boundaries
⏱️ 3:52
28.use Promises
⏱️ 3:24
29.Stream Promise Results from Server to Client
⏱️ 3:03
30.use Requires a Cached Promise
free
⏱️ 2:30
31.Suspense Error Boundaries
⏱️ 4:42
32.React Server Functions
⏱️ 4:50
33.Server Actions for Powerful Forms
⏱️ 5:35
34.useActionState to Simplify Form Actions
⏱️ 6:38
35.React Serializable Types
⏱️ 2:42
36.Create Dynamic Images with NextJS ImageResponse
⏱️ 5:54
37.Deploy NextJS Application to Production
⏱️ 3:51
38.NextJS Environment Variables Masterclass
⏱️ 3:50
39.Deploying and Managing Environment Variables
⏱️ 4:38
40.Using Databases for Dynamic Server Side State
free
⏱️ 7:34
41.Mastering NextJS Layout Files
⏱️ 4:54
42.Client State Management with NextJS
⏱️ 3:48
43.Client State Management In Action
⏱️ 8:04
44.Using Client State Management Libraries
⏱️ 5:25
45.Detecting Server vs Client Runtime and useEffect
⏱️ 4:33
46.Demystifying ISR vs SSR vs SSG
⏱️ 3:07
47.Static Site Generation or SSG with NextJS
⏱️ 3:16
48.Incremental Static Regeneration (ISR) Simplified
⏱️ 2:51
49.API Routes Caching with NextJS
⏱️ 3:05
50.Reference Guide to Caching for Modern NextJS
⏱️ 2:47
🚨 Work In Progress 🚧
Subscribe for Launch