Handle Form in React with TanStack Form

Nemesis Blog
5 min readSep 1, 2024

This time we will learn about how to handle a form in React with TanStack Form. In React you can use useState to handle form. However, the more complex the form, the more difficult it is to handle. To handle complex form you can use library like React Hook Form and Formik. Check this post if you using React Hook Form or Formik.

Prerequisite:

  • Next App Router / React App
  • Zod (for validation)
  • TanStack Form

To install Zod and TanStack form run this command:

npm i @tanstack/react-form
npm i @tanstack/zod-form-adapter zod

1. Basic Form

  • Using TanStack Form is very easy you just need to import useForm
  • Make sure that component is client component
  • Define default values with useForm to variable form
  • Render with form with form.Field
"use client"

import { useForm } from "@tanstack/react-form";

export default function Page() {
const form = useForm({
defaultValues: {
firstName: '',
},
onSubmit: async ({ value }) => {
console.log(value)
},
})


return (
<div className="w-fit p-4 bg-slate-100/10 rounded-lg border border-slate-800 mx-auto mt-40">
<form…

--

--