npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-form-action

v2.19.1

Published

State management helpers for the react form actions.

Readme

react-form-action

End-to-end typesafe success, error & validation state control for Next.js form actions.

Features

Action Creator

  • ✅ Provides envelope objects with "initial" | "invalid" | "success" | "failure" response types.
  • ✅ Define generic payload for each of the response type.
  • ✅ Bind action arguments.

tRPC-like Form Action builder

  • ✅ Define payload schema with the .input(zodSchema) to validate the formData
  • ✅ Reuse business logic with the .use(middleware) method.
  • ✅ Define bindable arguments with the .args([]) method.
  • ✅ Reuse error handling with the .error(handler).

React Context access with the <Action action={myFormAction} args={[...]} /> component

  • ✅ The React.useActionState() accessible via the useActionContext() hook.
  • ✅ Computes progress flags like isInvalid, isSuccess based on the envelope type.
  • ✅ Binds the action with the arguments from the args prop.
  • ✅ Has an optional validate prop to validate the form data client-side before calling the server action.
  • ✅ Enables you to reset the action state with the reset() callback.
  • ✅ useResetAction() hook (or <ResetAction /> component) to automatically initialize your action when the hook/component unmounts.

Context-bound <Form /> component

  • ✅ Reads the action from the <Action /> context.
  • ✅ Opt-out from the default form reset after action submit.

Install

npm i react-form-action zod-form-data

Getting Started

1️⃣ Create a Server Action

// app/subscribe/action.ts
"use server";

import { formAction } from "react-form-action";
import { z } from "zod";

export const subscribeAction = formAction
  .input(z.object({ email: z.email() }))
  .run(async ({ input }) => {
    return input.email;
  });

2️⃣ Create a Client Form Component

// app/subscribe/form.tsx
"use client";

import {
  Form,
  Submit,
  createComponents,
} from "react-form-action/client";

import { subscribeAction } from "./action";

const { FieldError, Success } = createComponents(subscribeAction);

export function SubscribeForm() {
  return (
    <Form>
      <Success>
        {({ isSuccess, data }) =>
          isSuccess && <p>✅ Please check your email :{data}.</p>
        }
      </Success>
      {/*💡 The FieldError "name" prop supports autocompletion */}
      <FieldError name="email">
        {({ name, error }) => (
          <input className={error ? "invalid" : ""} name={name} />
        )}
      </FieldError>
      <Submit>
        {({ pending, disabled }) => (
          <button type="submit" disabled={disabled}>
            {pending ? "🌀 Submitting..." : "Submit"}
          </button>
        )}
      </Submit>
    </Form>
  );
}

3️⃣ Provide the <Action> context on a Page

// app/subscribe/page.tsx
import { Action } from "react-form-action/client";

import { subscribeAction } from "./action";
import { SubscribeForm } from "./form";

export default function Page() {
  return (
    <Action action={subscribeAction}>
      <SubscribeForm />
    </Action>
  );
}

Usage

formAction builder

The zod-form-data powered action builder.

// app/actions/auth.ts
"use server";

import { formAction } from "react-form-action";
import { z } from "zod";
import { cookies } from "next/headers";

const i18nMiddleware = async () => {
  const { t } = await useTranslation("auth", cookies().get("i18n")?.value);
  // will be added to context
  return { t };
};

const authAction = formAction
  .use(i18nMiddleware)
  .use(async ({ ctx: { t } }) =>
    console.log("🎉 context enhanced by previous middlewares 🎉", t),
  )
  .error(async ({ error }) => {
    if (error instanceof DbError) {
      return error.custom.code;
    } else {
      // unknown error
      // default Next.js error handling (error.js boundary)
      throw error;
    }
  });

export const signIn = authAction
  .input(z.object({ email: z.email() }))
  // 🎉 extend the previous input (only without refinements and transforms)
  .input(z.object({ password: z.string() }))
  .run(async ({ ctx: { t }, input: { email, password } }) => {
    // Type inferred: {email: string, password: string}

    await db.signIn({ email, password });

    return t("verificationEmail.success");
  });

export const signUp = authAction
  .input(
    z
      .object({
        email: z.email(),
        password: z.string(),
        confirm: z.string(),
      })
      .refine((data) => data.password === data.confirm, {
        message: "Passwords don't match",
        path: ["confirm"],
      }),
  ) // if using refinement, only one input call is permited, as schema with ZodEffects is not extendable.
  .run(async ({ ctx: { t }, input: { email, password } }) => {
    // 🎉 passwords match!

    const tokenData = await db.signUp({ email, password });

    if (!tokenData) {
      return t("signUp.emailVerificationRequired");
    }

    return t("singUp.success");
  });

Args binding

The formAction builder supports action arguments binding:

import { formAction } from "react-form-action";

const i18nAction = formAction.args([z.enum("fr", "en")]);

export const updateUser = i18nAction
  .args([z.string().uuid()])
  .run(async ({ args: [_, userId] }) => {
    //          ^? ["fr" | "en", string]
    // ...
  })
  .error(({ args: [locale] }) => {
    return locale === "fr"
      ? "Échec de la mise à jour de l'utilisateur"
      : "Failed to update user";
  });
import { Action } from "react-form-action/client";
import { locale } from "next/root-params";

import { updateUser } from "./action";
import { UpdateUserForm } from "./form";

export default function Page({
  params,
}: PageProps<"/[locale]/update-user/[userId]">) {
  const { userId } = await params;

  return (
    <Action action={updateUser} args={[await locale(), userId]} >
      <UpdateUserForm />
    </Action>
  );
}

Action Context

The <Action> components enables you to access your action's state with the useActionContext() hook:

// 👉 Define standalone client form component (e.g. /app/auth/signup/SignUpForm.tsx)
"use client";

import { Action, Form, useActionContext } from "react-form-action/client";
import type { PropsWithChildren } from "react";

import { signupAction } from "./action";

function Pending({ children }: PropsWithChildren) {
  // read any state from the ActionContext:
  const {
    error,
    data,
    validationError,
    isPending,
    isFailure,
    isInvalid,
    isSuccess,
    isInitial,
  } = useActionContext();

  return isPending && children;
}

// 💡 render this form on your RSC page (/app/auth/signup/page.tsx)
export function SignupForm() {
  return (
    <Action action={signupAction}>
      <Form>
        <input name="email" />
        <input name="password" />
      </Form>
      {/* 🎆 Read the pending state outside the <Form> */}
      <Pending>
        {/* This renders only when the action is pending. 😎 */}
        <p>Please wait...</p>
      </Pending>
    </Action>
  );
}

Client-side validation

The <Action validate={} /> prop enables you to tap into the formData before they are passed to the server action.

"use client"; // NOTE: The <Action> renders a context provider (a client component)

import type { PropsWithChildren } from "react";
import { Action } from "react-form-action/client";
import { z } from "zod";
import { zfd } from "zod-form-data";
import { signUp } from "./action";
import { signUpSchema } from "./schema";

export function SignUpAction({ children }: PropsWithChildren) {
  return (
    <Action
      action={signUp}
      validate={(formData) => {
        const result = zfd.formData(signUpSchema).safeParse(formData);

        // NOTE: the return must be of the same type as your action's ValidationError type
        if (result.error) {
          return z.treeifyError(result.error);
        }

        return null;
      }}
    >
      {children}
    </Action>
  );
}

Use the validateSchema to avoid the zod-form-data boilerplate:

import { validateSchema } from "react-form-action";

import { signUpSchema } from "./schema";

export function SignUpAction({ children }: PropsWithChildren) {
  return (
    <Action
      action={signUp}
      validate={validateSchema(signUpSchema)}
    >
      {children}
    </Action>
  );
}

Automatic action state reset (when unmounting component)

Works with Next.js routing, where routes are wrapped in <Activity />.

"use client";

import type { PropsWithChildren } from "react";
import { Action, ResetAction } from "react-form-action/client";

import { updateUser } from "./action";

export function UpdateUserAction({ children }: PropsWithChildren) {
  return (
    <Action
      action={updateUser}
    >
      {/* IMPORTANT: must be rendered as a child of the <Action /> context. */}
      <ResetAction />
      {children}
    </Action>
  );
}

When you prefer hooks to JSX, you can use the useResetAction() usually in your forms:

import { Form, useResetAction } from "react-form-action/client";

function MyForm() {
  useResetAction();

  return <Form>...</Form>
}

<Form> Component

The <form> submits the action in onSubmit handler to prevent automatic form reset. Pass autoReset prop to use the action prop instead and keep the default reset.

"use client";

import { Action, Form } from "react-form-action/client";

import { updateUser } from "./action";

export function UpdateUserForm() {
  return (
    <Action action={updateUser}>
      <Form autoReset>{/* ... */}</Form>
    </Action>
  );
}

<Submit>

A render prop component for submit buttons. It combines the action pending state (from the <Action> context) with the native useFormStatus() of the enclosing <form>.

⚠️ Must be rendered within a <form> (e.g. the <Form> component) which is a descendant of <Action>.

The render prop receives the FormStatus fields (pending, data, method, action) and an additional disabled flag, which is true while the action is pending.

import type { ReactNode } from "react";
import { Action, Form, Submit } from "react-form-action/client";


// 👉 Use the <Submit> to define your custom SubmitButton: 
function SubmitButton({
  children,
  pendingLabel,
}: {
  children: ReactNode;
  pendingLabel: string;
}) {
  return (
    <Submit>
      {({ pending, disabled }) => (
        // 👉 `disabled` reflects the action state, `pending` the form submission
        <button type="submit" disabled={disabled}>
          {pending ? pendingLabel : children}
        </button>
      )}
    </Submit>
  );
}

// 👉 on submit, both buttons will be disabled but only the submitted one will have the pending label
function DecisionForm() {
  return (
    <Action action={decideAction}>
      <Form>
        <input type="hidden" name="decision" defaultValue="accept" />
        <SubmitButton pendingLabel="Accepting...">Accept</SubmitButton>
      </Form>
      <Form>
        <input type="hidden" name="decision" defaultValue="reject" />
        <SubmitButton pendingLabel="Rejecting...">Reject</SubmitButton>
      </Form>
    </Action>
  );
}

Context Bound Components createComponents()

Use the createComponents(action) helper to create components which use the ActionContext and have types bound to the action type.

<FielError> Component

"use client";

// ⚠️ createComponents is usable only in "use client" components
import { Form, createComponents } from "react-form-action/client";

import { authAction } from "./actions";

export const signUpAction = authAction
  .input(
    z
      .object({
        user: z.object({
          email: z.email(),
          name: z.string(),
        }),
        password: z.string().min(8),
        confirm: z.string(),
      })
      .refine((data) => data.password === data.confirm, {
        message: "Passwords don't match",
      }),
  )
  .run(async ({ ctx, input }) => {
    return null;
  });

// 🌟 The FieldError is now bound do the signUpAction input schema which allows autocompletion for its "name" prop
// ⚠️ Usable only with actions created with the formAction builder
const { FieldError } = createComponents(signUpAction);

export function SignUpForm() {
  return (
    <Action action={signUpAction}>
      <Form>
        {/* 1️⃣ When the "name" prop is an empty string, the top-level error will be rendered e.g.:
          "Passwords don't match" */}
        <FieldError name="" />
        {/* 2️⃣ Access fields by their name: */}
        <FieldError name="password" />
        <FieldError name="confirm" />
        {/* 3️⃣ Access nested fields by dot access notation: */}
        <FieldError name="user.email" />
      </Form>
    </Action>
  );
}

<Value>

Renders a hidden <input> with a fixed value, so a form can submit a value without a visible field. Use it to send the same form with different values, e.g. one submit button per decision.

Props:

  • name - the form field name. Like <FieldError>, it is typed to the paths of the action's input schema.
  • value - the string value submitted with the form.
  • Any other <input> attributes are passed through to the hidden input.
import { Action, Form, createComponents } from "react-form-action/client";

import { decisionAction } from "./actions";

// 🌟 The name prop is bound to the decisionAction input schema
const { Value } = createComponents(decisionAction);

export function DecisionForm() {
  return (
    <Action action={decisionAction}>
      <Form>
        {/* 👉 Submits decision=accept when the button is clicked */}
        <Value name="decision" value="accept" />
        <button type="submit">Accept</button>
      </Form>
      <Form>
        <Value name="decision" value="deny" />
        <button type="submit">Deny</button>
      </Form>
    </Action>
  );
}

<Success>

When children are JSX

import { Action, createComponents } from "react-form-action/client";

const { Success } = createComponents(signUpAction);

function MyForm() {
  return (
    <Action action={signUpAction}>
      <Success>
        {/* 👉 The message will render only after the action has succeeded */}
        <p>You've been signed up!</p>
      </Success>
    </Action>
  );
}

When children is a render prop

import { createComponents } from "react-form-action/client";

const { Success } = createComponents(signUpAction);

function Label({children}: PropsWithChildren) {
  return (
    <Success>
      {({ isSuccess, data }) => (
        {/* 👉 With a render prop, the children are always mounted, regardles of the isSuccess flag */}
        <label className={isSuccess ? "green" : ""}>
          {children}
        </label>
      )}
    </Success>
  );
};

<Pending>

Render children when the action is pending:

When children are JSX

import { Action, Pending } from "react-form-action/client";

import { Spinner } from "./components";

function MyForm() {
  return (
    <Action action={action}>
      {/* 👉 Unlike the React.useFormStatus() hook, we don't need here the <form> element at all. */}
      <Pending>
        {/* 👉 The spinner will UNMOUNT when the action is NOT pending */}
        <Spinner />
      </Pending>
    </Action>
  );
}

When children is a render prop

import { Pending } from "react-form-action/client";

function SubmitButton() {
  return (
    <Pending>
      {({ isPending }) => (
        {/* 👉 With a render prop, the children are always mounted, regardles of the isPending flag */}
        <button type="submit" disabled={isPending}>
          {isPending ? "Submitting..." : "Submit"}
        </button>
      )}
    </Pending>
  );
};

Action Creator

Low-level action creator, which provides the success, failure and invalid envelope constructors. With the createFormAction you must handle the native FormData by yourself.

"use server";

import { createFormAction } from "react-form-action";
import { z } from "zod";

// Define custom serializable error & success data types
type ErrorData = {
  message: string;
};

type SuccessData = {
  message: string;
};

type ValiationError = {
  name?: string;
};

const updateUserSchema = z.object({ name: z.string() });

export const updateUser = createFormAction<
  SuccessData,
  ErrorData,
  ValiationError
>(({ success, failure, invalid }) =>
  // success and failure helper functions create wrappers for success & error data respectively
  async (prevState, formData) => {
    if (prevState.type === "initial") {
      // use the initialData passed to <Form /> here
      // prevState.data === "foobar"
    }

    try {
      const { name } = updateUserSchema.parse({
        name: formData.get("name"),
      });

      const user = await updateCurrentUser(name);

      if (user) {
        // {type: "success", data: "Your profile has been updated.", error: null, validationError: null}
        return success({
          message: "Your profile has been updated.",
        });
      } else {
        // {type: "error", data: null, error: { message: "No current user." }, validationError: null}
        return failure({ message: "No current user." });
      }
    } catch (error) {
      if (error instanceof ZodError) {
        // {type: "invalid", data: null, error: null, validationError: {name: "Invalid input"}}
        return invalid({
          name: error.issues[0]?.message ?? "Validation error",
        });
      }

      return failure({ message: "Failed to update user." });
    }
  },
);

The action creator supports arguments binding:

export const updateUser = createFormAction(
  (
    { success, failure, invalid },
    userId: string /* Here you can specify multiple arguments */,
  ) =>
    async (prevState, formData) => {
      try {
        const { name } = updateUserSchema.parse({
          name: formData.get("name"),
        });

        const user = await db.users.findById(userId);

        if (!user) {
          return failure({ message: "No such user." });
        }

        const updated = await user.update({ name });

        if (updated) {
          return success({
            message: "User has been updated.",
          });
        } else {
          return failure({ message: "Failed to update." });
        }
      } catch (error) {
        // handle error
      }
    },
);

// call bind as usuall, the "123" becomes the "userId"
updateUser.bind(null, "123");