본문 바로가기
코딩이야기/Next.js 공부

[React] useFormStatus를 사용한 pending 상태 추적

by TaeHyeon0412 2024. 9. 9.

useFormStatus란?

  • React 18에서 도입된 서버 컴포넌트에서 비동기 폼 처리 상태를 관리하는 데 사용
  • 폼 제출 중, 폼 제출이 완료되었을 때 등의 상태를 추적

useFormStatus 훅은 자신이 위치한 컴포넌트가 폼의 자식이 되어야 하며, 부모 폼의 상태를 감지할 수 있어야 합니다.

 

Button 컴포넌트에 적용

export default function Button({
  large = false, //기본값
  onClick,
  type,
  text,
  ...rest
}: ButtonProps) {
  const { pending } = useFormStatus();
  //useFormStatus를 이용하여 부모 form의 pending상태를 알아냄
  //useFormStatus는 form의 자식만 쓸 수 있음

return type === "upload" ? (
    <button
      type="submit"
      disabled={pending}
      {...rest}
      className={cls(
        "py-2 px-4 border-2 border-gray-700 bg-gray-700 text-white  rounded-lg",
        pending
          ? "bg-gray-400"
          : "bg-blue-500 hover:bg-blue-900 hover:border-blue-900"
      )}
    >
      {pending ? "업로드 중.." : text}
    </button>
    .
    .
    .

 

오버레이 컴포넌트에 적용

import { useFormStatus } from "react-dom";

export default function UploadLayout() {
  const { pending } = useFormStatus();

  if (!pending) {
    return null;
  }

  return (
    <div className="fixed flex inset-0 items-center justify-center bg-black opacity-50 z-[99]">
      <span className="text-white">업로드 중...</span>
    </div>
  );
}

 

pending일 때 button, 오버레이 적용 

댓글 적용

 

 


이를 잘 응용하여 적용하면 pending 상태를 추적하여 사용자가 액션이 진행중인 것을 알 수 있어서 사용자 경험 개선에 중요한 역할을 할 것 같습니다.