useActionEffect: Effect wrapper on useActionState

Languages

typescript5.7.3

Libraries

effect3.12.4
react19.0.0
GithubCode

React 19 introduces the useActionState hook:

useActionState allows to execute any sync/async action while giving access to the action status (pending) and state (e.g. errors).

It's ideal to execute any action (even async) in response to submitting a form. But it can also be used with any payload, not only forms and FormData.

useActionEffect is a wrapper on useActionState using effect:

  • Accept any generic Payload
  • Execute any Effect with all dependencies included (extracted from CustomRuntime)
  • Report errors or success data inside the state of useActionState

The return type is the same as useActionState, so you can swap the two hooks without breaking other parts of the code.

The useInsertUser hook in the example snippet shows how to make a POST request with @effect/platform passing the FormData as body:

  • Specific the type of payload as FormData
  • data return type inferred from the returned value in the Effect
import { FetchHttpClient } from "@effect/platform";
import { Layer, ManagedRuntime } from "effect";

// 👇 Use `Layer.mergeAll` to add layers to `CustomRuntime`
const MainLayer = Layer.mergeAll(FetchHttpClient.layer);

export const CustomRuntime = ManagedRuntime.make(MainLayer);