Bird
Raised Fist0
NextJSframework~10 mins

Server action in client components in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Server action in client components
User clicks button
Client component calls server action
Server action runs on server
Server returns result
Client component updates UI
Shows how a client component triggers a server action, which runs on the server and returns data to update the UI.
Execution Sample
NextJS
'use client';

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  async function increment() {
    'use server';
    return 1;
  }

  async function handleClick() {
    const result = await increment();
    setCount(prevCount => prevCount + result);
  }

  return <button onClick={handleClick}>Count: {count}</button>;
}
A client component with a button that calls a server action to increment a count.
Execution Table
StepTriggerState BeforeActionState AfterWhat Re-rendersDOM Change
1Initial rendercount=0Render buttoncount=0Button with text 'Count: 0'Button text shows 'Count: 0'
2User clicks buttoncount=0Call handleClick -> calls server action incrementcount=0No immediate changeNo DOM change yet
3Server action runsN/Aincrement returns 1N/AN/AN/A
4handleClick resumescount=0setCount(0 + 1)count=1Button re-rendersButton text updates to 'Count: 1'
5User clicks button againcount=1Call handleClick -> calls server action incrementcount=1No immediate changeNo DOM change yet
6Server action runsN/Aincrement returns 1N/AN/AN/A
7handleClick resumescount=1setCount(1 + 1)count=2Button re-rendersButton text updates to 'Count: 2'
8No more clickscount=2No actioncount=2No re-renderNo DOM change
💡 Execution stops when user stops clicking; state stabilizes at count=2.
Variable Tracker
VariableStartAfter 1After 2Final
count0122
Key Moments - 3 Insights
Why does the UI update only after the server action finishes?
Because the server action runs asynchronously on the server, the client waits for its result before updating the state and re-rendering. See execution_table steps 2, 3, and 4.
Is the server action code running on the client?
No, server actions run only on the server. The client calls them asynchronously and waits for the response. This is shown in execution_table step 3.
Why is there no immediate UI change when the button is clicked?
Because the state update depends on the server action result, which takes time. The UI updates only after receiving the result, as in steps 4 and 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of count after step 4?
A0
B2
C1
DUndefined
💡 Hint
Check the 'State After' column at step 4 in the execution_table.
At which step does the server action return its result?
AStep 2
BStep 3
CStep 5
DStep 7
💡 Hint
Look for the step where 'increment returns 1' in the Action column.
If the server action returned 2 instead of 1, what would be the count after step 4?
A3
B1
C2
D0
💡 Hint
Refer to how setCount adds the server action result to count in step 4.
Concept Snapshot
Server actions run on the server but can be called from client components.
Client triggers server action asynchronously.
Server returns data, client updates state.
Use 'use server' directive inside server action.
UI updates only after server response.
Enables secure, fast server logic from client.
Full Transcript
This visual trace shows how a client component in Next.js calls a server action. When the user clicks the button, the client calls the server action asynchronously. The server action runs on the server and returns a result. The client waits for this result, then updates the state variable 'count' and re-renders the button with the new count. The execution table details each step, showing state before and after, and when the DOM updates. Key moments clarify why the UI updates only after the server action finishes and that server actions do not run on the client. The visual quiz tests understanding of state changes and server action timing. This helps beginners see how server actions integrate with client components in Next.js.

Practice

(1/5)
1. What is the main benefit of using server actions in Next.js client components?
easy
A. They enable client components to run only on the client side without server interaction.
B. They replace the need for React hooks in client components.
C. They allow client components to run server code securely without separate API routes.
D. They automatically convert client components into server components.

Solution

  1. Step 1: Understand server actions purpose

    Server actions let client components run server-side code directly, simplifying data handling.
  2. Step 2: Compare with API routes

    They remove the need for separate API routes by securely running server code from client components.
  3. Final Answer:

    They allow client components to run server code securely without separate API routes. -> Option C
  4. Quick Check:

    Server actions simplify server code use in client components = B [OK]
Hint: Server actions run server code from client without APIs [OK]
Common Mistakes:
  • Thinking server actions run only on client side
  • Confusing server actions with React hooks
  • Believing server actions convert client to server components
2. Which syntax correctly defines a server action in a Next.js client component?
easy
A. async function fetchData() { return await fetch('/api/data') }
B. export async function action() { 'use server'; /* server code */ }
C. function action() { 'use client'; /* client code */ }
D. const action = () => { return 'server action' }

Solution

  1. Step 1: Identify server action syntax

    Server actions require the 'use server' directive inside an async function to mark server code.
  2. Step 2: Check options for correct usage

    export async function action() { 'use server'; /* server code */ } correctly exports an async function with 'use server' directive, matching Next.js pattern.
  3. Final Answer:

    export async function action() { 'use server'; /* server code */ } -> Option B
  4. Quick Check:

    'use server' directive marks server action = A [OK]
Hint: Look for 'use server' directive inside async function [OK]
Common Mistakes:
  • Missing 'use server' directive in server action
  • Using 'use client' inside server action
  • Defining server action as non-async function
3. Given this code in a Next.js client component, what will happen when the button is clicked?
"use client";
import { useState } from 'react';
import { serverAction } from './actions';

export default function MyComponent() {
  const [message, setMessage] = useState('');

  async function handleClick() {
    const result = await serverAction();
    setMessage(result);
  }

  return (
    <>
      Click me
      

{message}

</> ); }
medium
A. The button click calls serverAction, updates message with its result, and displays it.
B. The button click causes a syntax error because serverAction cannot be called in client.
C. The message state never updates because serverAction runs only on server components.
D. The button click reloads the page instead of calling serverAction.

Solution

  1. Step 1: Understand serverAction usage in client component

    The client component imports and calls serverAction asynchronously on button click.
  2. Step 2: Analyze state update and rendering

    After awaiting serverAction, the result updates state 'message', which renders inside <p> tag.
  3. Final Answer:

    The button click calls serverAction, updates message with its result, and displays it. -> Option A
  4. Quick Check:

    Server action called and result shown = C [OK]
Hint: Server actions return data to client, update state to show result [OK]
Common Mistakes:
  • Assuming serverAction cannot be called from client
  • Forgetting async/await in handleClick
  • Expecting page reload on button click
4. Identify the error in this Next.js client component using a server action:
"use client";
import { serverAction } from './actions';

export default function Comp() {
  function handleClick() {
    const result = serverAction();
    console.log(result);
  }

  return Run;
}
medium
A. The component must use 'use server' directive instead of 'use client'.
B. serverAction cannot be imported into client components.
C. The button element must have an aria-label for accessibility.
D. handleClick must be async and await serverAction to get the result.

Solution

  1. Step 1: Check serverAction call in handleClick

    serverAction is async, so calling it without await returns a Promise, not the result.
  2. Step 2: Fix handleClick to async and await

    Making handleClick async and awaiting serverAction ensures correct result is logged.
  3. Final Answer:

    handleClick must be async and await serverAction to get the result. -> Option D
  4. Quick Check:

    Async function must await server action = D [OK]
Hint: Always await async server actions in client handlers [OK]
Common Mistakes:
  • Calling async server action without await
  • Thinking serverAction can't be imported in client
  • Ignoring accessibility best practices (not main error here)
5. You want to create a Next.js client component that uses a server action to submit a form and then reset the form fields. Which approach correctly combines server action usage and client state reset?
hard
A. Define an async server action with 'use server', call it in client handler with await, then reset state after await.
B. Call the server action without await, reset state immediately after calling it.
C. Use a server component instead of client component to handle form and reset state automatically.
D. Reset form state inside the server action function after processing data.

Solution

  1. Step 1: Understand server action and client state interaction

    Server actions run on server; client state reset must happen after server action completes.
  2. Step 2: Correct async handling and state reset

    Await server action call in client handler, then reset form state to ensure proper sequence.
  3. Final Answer:

    Define an async server action with 'use server', call it in client handler with await, then reset state after await. -> Option A
  4. Quick Check:

    Await server action before resetting client state = A [OK]
Hint: Await server action before resetting client form state [OK]
Common Mistakes:
  • Resetting state before awaiting server action
  • Trying to reset client state inside server action
  • Using server component instead of client for interactive form