
✅ useFormState(useActionState)
export default function LogIn() {
const [state, action] = useFormState(handleForm, null);
return (
<div className="flex flex-col gap-10 px-6 py-8">
<div className="flex flex-col gap-2 *:font-medium">
<h1 className="text-2xl">안녕하세요!</h1>
<h2 className="text-xl">Log in with email and password.</h2>
</div>
<form action={action} className="flex flex-col gap-3">
useFormState는 반환값으로 tuple을 주는데, state(action의 return값)와 formAction(server action trigger)이 들어있다.
그리고 useFormState의 인자값으로는 server action과 initialState이 들어간다.
form의 action 속성에 기존 server action이 아닌 trigger를 넣어줘야 useFormState에서 제공하는 정보를 받을 수 있다.
"use server";
export const handleForm = async (prevState: any, formData: FormData) => {
console.log(prevState);
await new Promise((resolve) => setTimeout(resolve, 5000));
return {
errors: ["wrong password", "password too short"],
};
};
server action은 첫 번째 인자로 prevState(이전 값)를 받을 수 있다.
React v19에서 useFormState의 이름이 useActionState로 변경되었다.
'♣️ Next.js 14' 카테고리의 다른 글
| Next.js 14 - Image component (0) | 2025.12.03 |
|---|---|
| Next.js 14 - Middleware, Matcher (0) | 2025.12.03 |
| Next.js 14 - useFormStatus (0) | 2025.09.17 |
| Next.js 14 - Server Action (0) | 2025.09.17 |
| Next.js 14 - api route (0) | 2025.09.17 |