DEV Community

Vitaliy Potapov
Vitaliy Potapov

Posted on • Updated on

Returning JSX from React Server Actions

Did you know that Next.js Server Actions can return React Components JSX instead of raw JSON data?

While it's not explicitly mentioned in the docs, I was pleasantly surprised that it works.

Example

I have a page that renders users list with server action:

export default function Page() {
  async function loadUsersAction() {
    "use server";

    return [
      { name: "John", age: 30 },
      { name: "Jane", age: 25 },
      { name: "Doe", age: 40 },
    ];
  }

  return <UsersList loadUsersAction={loadUsersAction} />;
}
Enter fullscreen mode Exit fullscreen mode

UsersList component loads users by button click:

'use client';

import { useState } from 'react';

export default function UsersList({ loadUsersAction }) {
  const [users, setUsers] = useState();

  const onClick = async () => {
    const data = await loadUsersAction();
    setUsers(data);
  };

  return (
    <>
      <button onClick={onClick}>Load users</button>
      <ul>
        {users?.map((user) => (
          <li key={user.name}>
            {user.name} - {user.age}
          </li>
        ))}
      </ul>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Demo:

Demo

Now I change server action to return JSX with rendered users:

async function loadUsersAction() {
  "use server";

  const users = [
    { name: "John", age: 30 },
    { name: "Jane", age: 25 },
    { name: "Doe", age: 40 },
  ];

  return (
    <ul>
      {users?.map((user) => (
        <li key={user.name}>
          {user.name} - {user.age}
        </li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

And in UsersList component just render server action response:

export default function UsersList({ loadUsersAction }) {
  const [users, setUsers] = useState();

  const onClick = async () => {
    const data = await loadUsersAction();
    setUsers(data);
  };

  return (
    <>
      <button onClick={onClick}>Load users</button>
      {users}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

In browser everything works in the same way!

Note on errors handling

What if server action throws an error? When it returns a JSON data, we can catch that error inside action and return it in own format like:

{ error: "my error" }
Enter fullscreen mode Exit fullscreen mode

When returning JSX, we can let error throw and catch it on the client with the nearest error boundary. As server action is called not inside a <form> element, it should be wrapped into Transition for proper errors handling. For Next.js it means that the nearest error.tsx file will be displayed in case of error.

The final code of UsersList component:

'use client';

import { useState, useTransition } from 'react';

export default function UsersList({ loadUsersAction }) {
  const [isPending, startTransition] = useTransition();
  const [users, setUsers] = useState();

  const onClick = () => {
    startTransition(async () => {
      const data = await loadUsersAction();
      setUsers(data);
    });
  };

  return (
    <>
      <button onClick={onClick}>Load users</button>
      {isPending ? <div>Loading users...</div> : users}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Additionally, I utilize isPending flag to show message while loading users.

Demo:
Demo

You can check out a fully working example on GitHub.
Thanks for reading and happy coding! ❤️

Top comments (3)

Collapse
 
itsjavidotcom profile image
Javi Aguilar • Edited

while it's very cool, where is the separation of concerns here?
what if in some years your company (or you) decides to refactor your code, ditch Nextjs, and go back to APIs?

my advice is treat actions like if they were API endpoints, also when it comes to security

Collapse
 
vitalets profile image
Vitaliy Potapov

I agree, it's more vendor lock, compared to traditional API calls. That's the payment for conveniency, a trade-off as always.
Personally, I think server actions will become more used in other frameworks, not only in Next.js. As they are core React feature and a part of Server Components, that will be stable in React 19.
I've checked Astro, it has similar actions approach.

Collapse
 
9opsec profile image
9opsec

Good easy to understand example!