React 19 New Hooks

robin Han·2025년 4월 27일
2

React 19 새로운 훅들

  • use()
  • useFormStatus()
  • useFormState() || useActionState()
  • useOptimistic()

Use()

context를 사용할때 기존에 사용하는 useContext훅들과 달리 use()훅은 루프 또는 조건문에서 사용이 가능해졌습니다.
Promise 또는 Context 값을 컴포넌트에서 조건문을 사용하면서 직접 읽을 수 있게 해주어서 비동기 데이터를 처리할수있다 .

비동기 데이터를 받을려면 useEffect안에서 fetch로 요청하거나 컴포넌트로 뺴너어서 훅을 따로 만들거나 해야하지만 use를 쓰면 이러한 과정없이 직접 읽어올수있다.

"use client";

import { use, Suspense } from "react";

function Message({ messagePromise }) {
 if(messagePromise){
 	const messageContent = use(messagePromise); 
 	return <p>Here is the message: {messageContent}</p>;
 }
 return null 
}
export function MessageContainer({ messagePromise }) {
 return (
   <Suspense fallback={<p>⌛Downloading message...</p>}>
     <Message messagePromise={messagePromise} />
   </Suspense>
 );
}

The use API returns the value that was read from the resource like the resolved value of a Promise or context.
use()

useFormStatus

폼의 제출 사탱를 하위 컴포넌트에서 접근 가능하게 해주는 훅으로 마지막으로 제출된 폼의 상태를 읽을수있다.

const { pending, data, method, action } = useFormStatus();

useFormStatus

useActionState (useFormState)

const [state, dispatch , isPending] = useActionState(
 async (prevState, formData) => {
   const error = await updateName(formData.get("name"));
   if (error) return error;
   redirect("/path");
   return null;
 }, // action
 null, // initialState 
 permalink //URL for form modification (optional) 
);

비동기 액션 처리한후 결과 상태에 대해서 관리 react query 와 비슷한 구조라고 생각한다, refetch, isPending을 추가적인 코드 없이 구현가능;

  • state : 현재 폼의 상태
  • dispatch : 폼안에서 액션을 트리거
  • isPending : boolean 폼액션이 진행중인지
  • action : 실제 실행되는 폼액션
  • initialState : 초기 폼값

useOptimistic

즉각적으로 UI를 업데이트를 해주는 역할로 isPending 인 서버상태에서 조금더 좋은 UX를 제공해준다

  const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
	const [optimisticState, addOptimistic] = useOptimistic(
    state,
    (currentState, optimisticValue) => {
      //return new state with optimistic value
    },
  );

따라서 서버로 부터 응답이 오기전에 UI 즉시 업데이하고 해당 응답이 실패하면 롤백한다
useOptimistic

이번에 나온 훅들은 전체적으로 비동기 처리 특히 폼에대한 처리와 그에대한 더나은 UX제공할수있게 해주는것 같습니다.

참고자료
https://www.freecodecamp.org/news/react-19-new-hooks-explained-with-examples/

0개의 댓글