Consider this Next.js server component with a form using a server action. What will the user see after submitting the form?
import { useState } from 'react'; export default function ContactForm() { async function handleSubmit(formData) { 'use server'; const name = formData.get('name'); return `Hello, ${name}! Your message was received.`; } return ( <form action={handleSubmit}> <input name="name" type="text" required aria-label="Name" /> <button type="submit">Send</button> </form> ); }
Think about how Next.js server actions handle form submissions and page updates.
In Next.js, a form with a server action submits and reloads the page. The returned string from the server action replaces the page content, so the user sees the greeting message.
Identify the correct syntax for a server action function used as a form action in Next.js.
The server action must be async and include the 'use server' directive at the top.
Server actions in Next.js require the 'use server' directive at the start of the async function to mark it as a server action.
Given this Next.js server component with a form and a server action that increments a count, what is the value of count after submitting the form twice?
import { useState } from 'react'; let count = 0; export default function CounterForm() { async function increment(formData) { 'use server'; count += 1; return count; } return ( <form action={increment}> <button type="submit">Increment</button> </form> ); }
Consider how server components and server actions handle state and variables.
Each server action runs in a fresh environment without preserving module-level variables. So 'count' resets to 0 each time, increments to 1, and returns 1 on every submission.
Examine this server action used as a form action. Why does submitting the form cause a runtime error?
export default function Form() { async function saveData(formData) { 'use server'; const age = formData.get('age'); if (age > 18) { return 'Adult'; } else { return 'Minor'; } } return ( <form action={saveData}> <input name="age" type="number" aria-label="Age" /> <button type="submit">Check</button> </form> ); }
Think about the data type returned by formData.get and how JavaScript compares different types.
formData.get returns a string. Comparing a string to a number with '>' causes unexpected behavior or runtime errors. The age should be converted to a number first.
Choose the correct statement about how Next.js handles form actions with server functions.
Recall where server actions execute and how form submissions behave in Next.js.
Server actions run on the server. When used as form actions, they cause a full page reload by default to show the updated content.