Bird
Raised Fist0
NextJSframework~20 mins

Server action in client components in NextJS - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Server Action Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a server action is called inside a client component?
Consider a Next.js client component that calls a server action on a button click. What is the expected behavior of the component after the server action completes?
NextJS
import { useState } from 'react';
'use client';

async function addItem(data) {
  'use server';
  // Imagine this adds data to a database
  return 'Item added';
}

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

  async function handleClick() {
    const result = await addItem({ name: 'New Item' });
    setMessage(result);
  }

  return (
    <>
      <button onClick={handleClick}>Add Item</button>
      <p>{message}</p>
    </>
  );
}
AThe button click triggers the server action, and the component updates the message with 'Item added' without a full page reload.
BThe server action runs on the client, causing a runtime error because server code cannot run in the browser.
CThe component reloads the entire page after the server action completes to update the UI.
DThe server action is ignored because client components cannot call server actions.
Attempts:
2 left
💡 Hint
Think about how Next.js handles server actions called from client components asynchronously.
📝 Syntax
intermediate
1:30remaining
Identify the correct syntax to define a server action in Next.js
Which of the following code snippets correctly defines a server action that can be called from a client component?
Aasync function saveData() { 'use client'; /* server code */ }
Bfunction saveData() { 'use client'; /* server code */ }
Casync function saveData() { 'use server'; /* server code */ }
Dfunction saveData() { 'use server'; /* client code */ }
Attempts:
2 left
💡 Hint
Server actions must be async functions with a special directive.
🔧 Debug
advanced
2:00remaining
Why does this server action call cause a runtime error in a client component?
Examine the code below. Why does calling the server action cause a runtime error in the client component?
NextJS
import { useState } from 'react';
'use client';

function deleteItem(id) {
  'use server';
  // delete logic
}

export default function DeleteButton() {
  const [deleted, setDeleted] = useState(false);

  function handleDelete() {
    deleteItem(1);
    setDeleted(true);
  }

  return <button onClick={handleDelete}>{deleted ? 'Deleted' : 'Delete'}</button>;
}
AThe server action must be imported from a separate server file, not defined inline.
BThe client component cannot use useState with server actions.
CThe 'use server' directive is misplaced; it should be outside the function.
DThe server action is called without await, so it runs on the client causing a runtime error.
Attempts:
2 left
💡 Hint
Consider how async server actions must be called from client components.
state_output
advanced
1:30remaining
What is the value of 'count' after calling this server action in a client component?
Given the code below, what will be the value of 'count' displayed after clicking the button once?
NextJS
import { useState } from 'react';
'use client';

let serverCount = 0;

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

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

  async function handleClick() {
    const newCount = await increment();
    setCount(newCount);
  }

  return <button onClick={handleClick}>Count: {count}</button>;
}
ACount: 0
BCount: 1
CCount: NaN
DCount: undefined
Attempts:
2 left
💡 Hint
Think about where serverCount is stored and how server actions update it.
🧠 Conceptual
expert
2:30remaining
Why must server actions be async functions in Next.js client components?
Select the best explanation for why server actions are defined as async functions when used in client components.
ABecause server actions run on the server and communicate asynchronously with the client, so they must return promises.
BBecause JavaScript requires all server-side code to be async functions.
CBecause client components cannot handle synchronous functions at all.
DBecause async functions automatically cache server responses in Next.js.
Attempts:
2 left
💡 Hint
Think about how client and server communicate 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