useActionstate
2025. 5. 15. 23:24ㆍCoding Study/React
useActionState
useActionState 는 인자로 3개의 인자를 반환한다.
const [state, formAction, isPending] = useActionState( handleSubmit, null )
- 이 훅은 actionFunction이 실행된 결과 상태(state)를 추적하고,
- 그 액션을 트리거할 수 있는 함수(formAction)를 리턴하며,
- 현재 실행 중인 상태인지를 알려주는 isPending도 함께 제공한다.
1. state
액션 실행 후의 결과 상태. 예를 들어, 서버에서 리턴된 메시지나 에러 등이 여기에 담긴다. 처음에는 null이다.
2. formAction
handlrSubmit 을 실제로 실행시킬 수 있는 함수. <form action={formAction}>처럼 사용한다..
3. isPending
true일 경우, 현재 createReviewAction이 실행 중이라는 의미다. 로딩 스피너 같은 걸 보여줄 때 사용한다
import { useActionState } from "react";
function App() {
const handleSubmit = async (state, formData) => {
const name = formData.get("name");
const email = formData.get("email");
const age = formData.get("age");
const comment = formData.get("comment");
await new Promise((resolve) => setTimeout(resolve, 2000));
const message = `${name}(${email}, ${age}세)님의 메시지: "${comment}" 제출 완료!`;
return message;
};
const [state, formAction, isPending] = useActionState(handleSubmit, null);
return (
<div>
<form action={formAction} className="container">
<input name="name" placeholder="이름" />
<input name="email" placeholder="이메일" />
<input name="age" placeholder="나이" />
<input name="comment" placeholder="코멘트" />
<button disabled={isPending}>
{isPending ? "제출 중..." : "제출"}
</button>
</form>
{state && <p>{state}</p>}
</div>
);
}
export default App;
'Coding Study > React' 카테고리의 다른 글
| 회원 가입 페이지 Joi , react-hook-form 을 사용한 유효성 검증 (4) | 2025.08.10 |
|---|---|
| Joi (유효성 검증 라이브러리) (1) | 2025.08.09 |
| react 어플리케이션 성능 최적화 (1) | 2025.04.24 |
| 번들링과 코트스플리팅 (1) | 2025.04.24 |
| Redux ToolKit (0) | 2025.04.22 |