useActionState 데모
useActionState 훅을 사용하면 [state, action, pending]을 반환받아 pending 상태를 손쉽게 관리할 수 있습니다. 버튼을 클릭하면 2초간 pending 상태가 유지됩니다.
핵심 코드
// _components/PendingButton.tsx
'use client'
import { useActionState, startTransition } from 'react'
import { createPost } from '../actions'
export default function PendingButton() {
const [state, action, pending] = useActionState(
createPost, false
)
await connection();
return (
<button onClick={() => startTransition(action)}>
{pending ? <LoadingSpinner /> : 'Create Post'}
</button>
)
}체험 포인트: 버튼을 클릭하면 pending이 true로 변하면서 로딩 스피너가 표시됩니다. 2초 후 Server Action이 완료되면 state가 true로 변하고 pending이 false로 돌아갑니다.