DEV Community

KentaroMorishita
KentaroMorishita

Posted on

Simplifying Form Management in React: useActionState vs useRBoxForm

I will introduce a comparison between React 19 new hook useActionState and useRBoxForm from my library f-box-react.

I'll explain the characteristics of each approach to form state management and how to get started with useRBoxForm.

Table of Contents

  1. Introduction
  2. Introducing useActionState
  3. Introducing f-box-react and useRBoxForm
  4. Comparison: Differences in Usability
  5. Installing and Setting Up f-box-react
  6. Conclusion

Introduction

React 19's new hook, useActionState, simplifies form submissions and the management of their resulting state. On the other hand, my library f-box-react provides a more advanced form management hook called useRBoxForm.
In this article, I'll compare these two hooks and share how useRBoxForm can help simplify and enhance your form management.

Introducing useActionState

React 19 introduced useActionState, a hook that provides a simple flow for handling form submissions:

import { useActionState } from "react"

type FormState = {
  success?: boolean
  cartSize?: number
  message?: string
}

function addToCart(prevState: FormState, queryData: FormData) {
  const itemID = queryData.get("itemID")
  if (itemID === "1") {
    return {
      success: true,
      cartSize: 12,
    }
  } else {
    return {
      success: false,
      message: "The item is sold out.",
    }
  }
}

function AddToCartForm({
  itemID,
  itemTitle,
}: {
  itemID: string
  itemTitle: string
}) {
  const [formState, formAction, isPending] = useActionState<
    FormState,
    FormData
  >(addToCart, {})

  return (
    <form action={formAction}>
      <h2>{itemTitle}</h2>
      <input type="hidden" name="itemID" value={itemID} />
      <button type="submit" disabled={isPending}>
        Add to Cart
      </button>
      {formState?.success && (
        <div>Item added to cart! Current cart size: {formState.cartSize}</div>
      )}
      {formState?.success === false && (
        <div>Failed to add item: {formState.message}</div>
      )}
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

While useActionState provides a simple mechanism for updating form state via a callback function, its drawback is that the responsibility for managing state is concentrated in a single object. This can become problematic as complexity grows.

Introducing f-box-react and useRBoxForm

f-box-react is a library that integrates the reactive capabilities of RBox with React. Among its features is useRBoxForm, a hook specifically designed for form management, which distinctly separates form data, validation logic, and error message handling, enabling cleaner and more maintainable form handling.

For example, here's a sample using useRBoxForm:

import { useRBoxForm } from "f-box-react"

type Form = {
  itemID: string
  cartSize: number
}

const validate = (form: Form) => ({
  itemID: [() => form.itemID === "1"],
  cartSize: [],
})

function AddToCartForm({
  itemID,
  itemTitle,
}: {
  itemID: string
  itemTitle: string
}) {
  const {
    form,
    edited,
    isPending,
    handleChange,
    handleValidatedSubmit,
    shouldShowError,
  } = useRBoxForm<Form>({ itemID, cartSize: 0 }, validate)

  const handleSubmit = handleValidatedSubmit(async (form) => {
    if (form.itemID === "1") {
      handleChange("cartSize", 12)
    }
  })

  return (
    <form onSubmit={handleSubmit}>
      <h2>{itemTitle}</h2>
      <button type="submit" disabled={isPending}>
        Add to Cart
      </button>
      {edited.itemID &&
        (shouldShowError("itemID")(0) ? (
          <div>Failed to add to cart: The item is sold out.</div>
        ) : (
          <div>Item added to cart! Current cart size: {form.cartSize}</div>
        ))}
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

With useRBoxForm, you can clearly separate the logic for updating form state, handling validation, and displaying error messages, resulting in code that's easier to manage.

Comparison: Differences in Usability

With useActionState

  • Simple Design
    It manages form submission results within a single object, which is very straightforward to understand when you're just starting out.

  • Concentrated Responsibilities
    Having success flags, messages, and cart size all in one object can make it hard to know where to make changes as features increase.

  • Challenging to Extend
    When state changes or validations become complex, adapting flexibly can feel difficult.

With useRBoxForm

  • Clear Separation of Roles
    By handling form data, validation logic, and error messages separately, it's clear where to make changes.

  • Ease of Use
    Since each function is independent, modifying one part doesn't affect others, keeping overall code simple.

  • Type Safety and Confidence
    With TypeScript defining clear types for form data and validation, unexpected errors are less likely, making development smoother.

  • Reusability
    Once you create logic for managing a form, it can easily be reused across different forms.

Overall, useRBoxForm allows you to manage complex state more comfortably by separating each concern.

Installing and Setting Up f-box-react

1. Installing f-box-react

You can install f-box-react using npm or yarn:

# Using npm
npm install f-box-react

# Using yarn
yarn add f-box-react
Enter fullscreen mode Exit fullscreen mode

2. Basic Usage

Import the useRBoxForm hook from f-box-react and use it in your form component:

import { useRBoxForm } from 'f-box-react';

type Form = {
  // Define your form fields here
};

const validate = (form: Form) => ({
  // Define validation rules here
});

function MyFormComponent() {
  const { form, handleChange, handleValidatedSubmit, /* other returned values */ } =
    useRBoxForm<Form>(/* initial values */, validate);

  // Write your form JSX here
}
Enter fullscreen mode Exit fullscreen mode

For more detailed usage and advanced examples, check out the GitHub repository or the official documentation at https://f-box-docs.com.

Conclusion

There are many approaches to managing form state in React. While useActionState is appealing for its simplicity, it can become unwieldy as complexity increases. In contrast, useRBoxForm from f-box-react separates form data, validation, and error messages, offering an easier-to-manage and more extensible solution.

I hope this article gives you insight into the appeal and usage of f-box-react. Although it's not widely known yet, I encourage you to try it out!

Top comments (0)