Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

react-hook-form

БесплатноБез исполняемых скриптовНе проверен

React Hook Form is a React library for building forms with uncontrolled inputs, so typing does not re-render the whole form. Use when the user wants form…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

React Hook Form

Overview

React Hook Form (RHF) keeps input values in refs instead of React state, so a form re-renders only when its validation state or a watched value changes. register connects an input, handleSubmit runs validation and calls your function with typed data, and a resolver plugs in a schema library such as Zod. These examples use Zod 4 (z.email()); with Zod 3 write z.string().email().

Instructions

Step 1: Install

npm install react-hook-form @hookform/resolvers zod

If npm stops with an ERESOLVE error about optional peer dependencies of @hookform/resolvers, rerun with --legacy-peer-deps, or use pnpm or yarn.

Step 2: Form with Zod validation

Give each input an id that matches its label, set defaultValues for every field (RHF warns about uncontrolled-to-controlled switches otherwise), and use setError for failures that only the server can detect. errors.root holds form-level errors.

// SignupForm.tsx
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'

export const signupSchema = z
  .object({
    name: z.string().min(2, 'Name must be at least 2 characters'),
    email: z.email('Invalid email address'),
    password: z
      .string()
      .min(8, 'Password must be at least 8 characters')
      .regex(/[A-Z]/, 'Must contain an uppercase letter')
      .regex(/[0-9]/, 'Must contain a number'),
    confirmPassword: z.string(),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ['confirmPassword'],
  })

type SignupInput = z.infer<typeof signupSchema>

export function SignupForm({ onCreated }: { onCreated: () => void }) {
  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting },
  } = useForm<SignupInput>({
    resolver: zodResolver(signupSchema),
    defaultValues: { name: '', email: '', password: '', confirmPassword: '' },
  })

  const onSubmit = async (data: SignupInput) => {
    const res = await fetch('/api/auth/signup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    })
    if (res.status === 409) {
      setError('email', { message: 'This email is already registered' })
      return
    }
    if (!res.ok) {
      setError('root', { message: 'Signup failed, try again' })
      return
    }
    onCreated()
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate>
      <label htmlFor="name">Name</label>
      <input id="name" {...register('name')} />
      {errors.name && <p role="alert">{errors.name.message}</p>}

      <label htmlFor="email">Email</label>
      <input id="email" type="email" autoComplete="email" {...register('email')} />
      {errors.email && <p role="alert">{errors.email.message}</p>}

      <label htmlFor="password">Password</label>
      <input id="password" type="password" autoComplete="new-password" {...register('password')} />
      {errors.password && <p role="alert">{errors.password.message}</p>}

      <label htmlFor="confirmPassword">Confirm password</label>
      <input id="confirmPassword" type="password" autoComplete="new-password" {...register('confirmPassword')} />
      {errors.confirmPassword && <p role="alert">{errors.confirmPassword.message}</p>}

      {errors.root && <p role="alert">{errors.root.message}</p>}
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Creating account...' : 'Sign Up'}
      </button>
    </form>
  )
}

Step 3: Dynamic fields

useFieldArray manages the list; always use field.id as the React key, not the index. Read live values with useWatch inside a small child component so only that part re-renders. valueAsNumber turns number inputs into numbers.

// InvoiceForm.tsx
import { useForm, useFieldArray, useWatch } from 'react-hook-form'

interface InvoiceValues {
  clientName: string
  items: Array<{ description: string; quantity: number; price: number }>
}

function InvoiceTotal({ control }: { control: ReturnType<typeof useForm<InvoiceValues>>['control'] }) {
  const items = useWatch({ control, name: 'items' })   // only this component re-renders
  const total = items.reduce((sum, item) => sum + (item.quantity || 0) * (item.price || 0), 0)
  return <p>Total: ${total.toFixed(2)}</p>
}

export function InvoiceForm({ onSave }: { onSave: (values: InvoiceValues) => void }) {
  const { register, control, handleSubmit } = useForm<InvoiceValues>({
    defaultValues: { clientName: '', items: [{ description: '', quantity: 1, price: 0 }] },
  })
  const { fields, append, remove } = useFieldArray({ control, name: 'items' })

  return (
    <form onSubmit={handleSubmit(onSave)}>
      <input {...register('clientName')} placeholder="Client name" />

      {fields.map((field, index) => (
        <div key={field.id}>
          <input {...register(`items.${index}.description`)} place
Полный SKILL.md на GitHub

Установить react-hook-form в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл react-hook-form?

React Hook Form is a React library for building forms with uncontrolled inputs, so typing does not re-render the whole form. Use when the user wants form validation in React or Next.js, a signup or checkout form with Zod, dynamic field lists with useFieldArray, server-side errors mapped onto fields, or fewer re-renders from watch.

Как установить скилл react-hook-form?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл react-hook-form запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить react-hook-form с