C.W.K.
Stream
Lesson 03 of 08 · published

useActionState

~22 min · useActionState, form state, errors

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

React 19 에서 rename

react-domuseFormState 가 사라짐. reactuseActionState 사용. 새 hook 이 세 번째 값 isPending 도 반환 — submit button 비활성화 common case 위해 useFormStatus 더 안 필요.

모양

const [state, formAction, isPending] = useActionState(action, initialState);state render, formAction form 에 넘김, isPending 동안 비활성.

Action signature

Action 이 (prevState, formData) 받고 다음 state 반환. 반환하는 게 다음 render 의 state. 이게 "action 돌았어, 이렇게 됐어" channel: success message, validation error, optimistic marker.

Code

Sign-up form 의 useActionState·tsx
'use client';
import { useActionState } from 'react';

async function signUp(prev: any, formData: FormData) {
  'use server';
  const email = formData.get('email') as string;
  if (!email.includes('@')) return { error: 'Invalid email', success: false };

  await db.user.create({ data: { email } });
  return { error: null, success: true };
}

export default function SignUpForm() {
  const [state, formAction, pending] = useActionState(signUp, {
    error: null,
    success: false,
  });

  return (
    <form action={formAction} className="space-y-2">
      <input name="email" type="email" required className="border px-2 py-1" />
      {state.error && <p className="text-red-500 text-sm">{state.error}</p>}
      {state.success && <p className="text-green-600 text-sm">Welcome!</p>}
      <button disabled={pending} className="rounded bg-blue-600 px-3 py-1 text-white">
        {pending ? 'Signing up&hellip;' : 'Sign up'}
      </button>
    </form>
  );
}

External links

Exercise

react-domuseFormState 쓰는 form 을 reactuseActionState 로 변환. Diff 보여주고 pending state 가 이제 hook 자체에서 오는지 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.