Server Actions and the experimental useFormStatus hook
June 2023·3 min read·
Today, we experiment with the newly released Server Actions and the experimental_useFormStatus hook.
Because our Form is a Client Component, we'll need to move the action into a separate actions.ts file with the "use server" directive. This is totally fine and I might use it even in Server Components to keep make it easier to switch a file from RSC to RCC and to separate the concerns.
For testing purposes, we set a timeout of 2000ms to display a loading state and simulate a database connection.
Let's have a closer look to the form component. You will quickly notice that we are using a Client Component with the main purpose of detecting and mutating the incoming searchParams.
All the non-rendering part is optional but makes the form feel interactive.
You might have noticed that we redirect the form action to /?form=success&email=${email} which allows us to create a toast to notify the user on the form status, which in our case always succeeded. Once done, we are reseting the search parameters. In case the user accidentally refreshes the page, we won't show him again the toast notification.
Now you might wonder why we need a separate SubmitButton. This is because the current useFormStatus seems to not work in the same file as the Form. As simple as that. And I couldn't figure out the specific reason, as both components are Client Components.
The loading animation is inspired by the vercel's one. It's build with tailwind-animate which is added to ui.shadcn by default. Otherwise we could easily extend the tailwind.config.js with utilities. Let me know if you have any questions. I won't go deeper into it!