Consider a Next.js 14 component using a server action to update a counter. What will the displayed counter value be after clicking the button once?
import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); async function increment() { 'use server'; setCount(count + 1); } return ( <> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </> ); }
Remember that server actions run on the server and cannot directly update client state hooks.
Server actions run on the server and cannot directly modify client-side React state like useState. The setCount call inside the server action does nothing on the client. To update client state, you must handle the update on the client or refresh the data after the server action completes.
Identify the correct syntax to define a server action function in Next.js 14.
Server actions must be async and include the 'use server' directive.
Server actions in Next.js 14 must be async functions and include the 'use server' directive at the top of the function body. This tells Next.js to run the function on the server.
Given this Next.js 14 component with a server action, why does the browser console show a hydration mismatch error?
import { useState } from 'react'; export default function Toggle() { const [on, setOn] = useState(false); async function toggle() { 'use server'; setOn(!on); } return ( <> <p>{on ? 'ON' : 'OFF'}</p> <button onClick={toggle}>Toggle</button> </> ); }
Think about how server actions and client state interact during rendering.
The server action runs on the server and cannot update client state directly. Calling setOn inside the server action does not update the client state, so the server-rendered HTML and client-rendered HTML differ, causing a hydration mismatch error.
count after this server action completes?In this Next.js 14 component, what will be the value of count after clicking the button once?
import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); async function increment() { 'use server'; // pretend to save to database return count + 1; } return ( <> <p>Count: {count}</p> <button onClick={async () => { const newCount = await increment(); setCount(newCount); }}>Increment</button> </> ); }
Note how the server action returns a value and the client updates state with it.
The server action returns count + 1 which is 1 initially. The client awaits this value and then calls setCount(1), so the displayed count updates to 1.
Select the true statement about server actions in Next.js 14.
Think about where server actions run and how they interact with client components.
Server actions run on the server and can be called from client components to perform server-side logic like database updates. They cannot directly modify client React state hooks, must be async, and do not automatically update client UI without client-side state management.