0
0
NextJSframework~30 mins

Use server directive in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the 'use server' Directive in Next.js 14
📖 Scenario: You are building a simple Next.js 14 app where you want to handle a form submission on the server side using the new use server directive.This helps keep your server logic separate and secure while using React Server Components.
🎯 Goal: Create a Next.js 14 component that uses the use server directive to define a server action function. This function will handle a form submission and update a message displayed on the page.
📋 What You'll Learn
Create a React Server Component with a form
Define a server action function using the use server directive
Use the server action function as the form's action handler
Display a message updated by the server action
💡 Why This Matters
🌍 Real World
Using the 'use server' directive lets you write server-only logic in Next.js 14 apps, improving security and performance by keeping sensitive code on the server.
💼 Career
Understanding server actions and React Server Components is essential for modern Next.js development roles, enabling you to build scalable and secure web applications.
Progress0 / 4 steps
1
Create the basic React Server Component with a form
Create a React Server Component called MessageForm that returns a form with a single text input named message and a submit button labeled Send. The form should have no action yet.
NextJS
Need a hint?

Start by writing a function named MessageForm that returns JSX with a form, input, and button.

2
Add a server action function with the 'use server' directive
Inside the MessageForm component file, define a function called handleSubmit that uses the "use server" directive at the top of its body. This function should accept a FormData parameter and extract the message field from it.
NextJS
Need a hint?

Write an async function named handleSubmit with formData parameter. Add "use server"; at the start of the function body.

3
Connect the server action function to the form's action attribute
Modify the form element to use the handleSubmit function as its action attribute. This will make the form submit call the server action.
NextJS
Need a hint?

Add action={handleSubmit} inside the <form> tag.

4
Add state to display the submitted message
Add a React useState hook called submittedMessage initialized to an empty string. Update the handleSubmit function to set submittedMessage to the submitted message string. Display submittedMessage below the form inside a <p> tag.
NextJS
Need a hint?

Import useState from React. Create state variables and update the state inside handleSubmit. Show the message below the form.