Kết hợp React Hook Form với Server Actions là cặp bài trùng mạnh mẽ nhất hiện nay.
1. Vấn đề của cách cũ (API Route)
- Client:
onSubmit->fetch('/api/login'). - Server: Parse Body -> Validate -> Return JSON.
- Client:
await res.json()->if (error) setError(). -> Rất nhiều boilerplate code ở cả 2 đầu.
2. Cách mới: Server Actions + useActionState (React 19)
Trong React 19, useActionState (trước đây là useFormState) giúp quản lý state của Form Action cực nhàn.
tsx:
// actions.ts
'use server';
export async function loginAction(prevState: any, formData: FormData) {
// Validate bằng Zod ở Server
const result = LoginSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
return {
success: false,
errors: result.error.flatten().fieldErrors
};
}
// Login logic...
return { success: true, message: "Login thành công!" };
}tsx:
// LoginForm.tsx
'use client';
import { useActionState } from 'react';
import { useForm } from 'react-hook-form';
export function LoginForm() {
// state chứa kết quả trả về từ server (errors, success)
const [state, formAction, isPending] = useActionState(loginAction, null);
// Vẫn dùng RHF để quản lý input và validate client-side
const { register } = useForm();
return (
// formAction của React 19 đấu trực tiếp vào prop action
<form action={formAction}>
<input {...register("email")} name="email" />
{/* Hiển thị lỗi từ Server trả về */}
{state?.errors?.email && (
<p className="text-red-500">{state.errors.email[0]}</p>
)}
<button disabled={isPending}>
{isPending ? "Đang đăng nhập..." : "Login"}
</button>
</form>
);
}3. Progressive Enhancement
Điểm tuyệt vời: Form này hoạt động ngay cả khi JavaScript chưa tải xong (hoặc bị tắt). Trình duyệt sẽ gửi POST request truyền thống, Server Action xử lý và trả về HTML mới. User không bao giờ bị kẹt.
Kết luận
Sự kết hợp giữa React Hook Form (Client Validation, UX mượt) và Server Actions (Server Validation, Security) tạo nên trải nghiệm Form đẳng cấp: Nhanh, An toàn, và Robust.