React 19에서 등장할 새로운 Client Side Hooks

상현·2024년 3월 25일
3

React

목록 보기
21/24
post-thumbnail

React 19가 등장하며 새로운 Client Side Hooks들이 생겼다.

useOptimistic, useFormStatus, useFormStateuse()라는 특이한 이름의 hook이다

useOptimistic

공식문서 https://react.dev/reference/react/useOptimistic#noun-labs-1201738-(2)

useOptimistic hook은 UI를 낙관적으로 업데이트 시켜주는 것을 도와주는 hook이다.
즉, 비동기 통신을 통한 업데이트를 해야하는 state에 대해 낙관적 업데이트를 함으로써 사용자 경험을 향상 시킬 수 있다.

예를 들어, 좋아요 기능이나, 장바구니 같은 것들이 있겠다.

import { useOptimistic } from 'react';

function AppContainer() {
  const [optimisticState, addOptimistic] = useOptimistic(
    state,
    // updateFn
    (currentState, optimisticValue) => {
      // merge and return new state
      // with optimistic value
    }
  );
}
  • state: 초기값
  • updateFn(currentState, optimisticValue): addOptimistic에 optimistic update될 값을 전달하고, 그 값을 반환한다. 순수 함수여야 한다.

useFormStatus

공식문서: https://react.dev/reference/react-dom/hooks/useFormStatus#noun-labs-1201738-(2)

useFormStatus 은 Form의 마지막 제출 상태를 제공하는 Hook이다.

반환값

  • pending: boolean 타입이 반환되며, true면 현재 제출이 pending이라는 뜻입니다.

  • data: form이 제출 중인 데이터를 포함하는 FormData interface를 구현하는 객체입니다. form이 없거나 제출이 없는 경우에는 null입니다.

  • 메서드: 'get' 또는 'post'의 문자열 값입니다.

  • action: form의 액션 프로퍼티에 전달된 함수에 대한 참조입니다.

const { pending, data, method, action } = useFormStatus();
import { useFormStatus } from "react-dom";
import action from './actions';

function Submit() {
  const status = useFormStatus();
  return <button disabled={status.pending}>Submit</button>
}

export default function App() {
  return (
    <form action={action}>
      <Submit />
    </form>
  );
}

useFormState

공식문서: https://react.dev/reference/react-dom/hooks/useFormState#noun-labs-1201738-(2)

useFormState는 form action의 결과에 따라 상태가 업데이트 될 수 있는 Hook이다.

parameter

  • fn: form 제출이나, 버튼이 눌렸을 때 호출할 함수이다. 함수가 호출되면 함수에서 반환한 값이 전달된다.

  • initialState: 초기값

import { useFormState } from "react-dom";

async function increment(previousState, formData) {
  return previousState + 1;
}

function StatefulForm({}) {
  const [state, formAction] = useFormState(increment, 0);
  return (
    <form>
      {state}
      <button formAction={formAction}>Increment</button>
    </form>
  )
}

use()

공식문서: https://react.dev/reference/react/use#noun-labs-1201738-(2)

usePromiseContext같은 값을 읽는 것을 도와주는 Hook이다.

<Susnpense />와 같이 사용할 수 있으며 아래 예제를 보면 더 쉽게 사용 방법을 알수 있다.

const NewsContainer = ({ newsPromise }) => (
  <Suspense fallback={<p>Fetching the news...</p>}>
    <News newsPromise={newsPromise} />
  </Suspense>
);

const News = ({ newsPromise }) => {
  const news = use<string[]>(newsPromise);
  return (
    <ul>
      {news.map((title, index) => (
        <li key={index}>{title}</li>
      ))}
    </ul>
  );
};

use안의 Promise가 Pending 상태면 Fallback 컴포넌트를 보여준다.
useEffect나 어떤 것도 쓰지 않고 비동기 데이터를 호출하고 보여줄 수 있게 되었다.

또한 use는 다른 Hook들과는 다른 특별한 점이 있다. 바로 iffor문 같은 조건, 반복문 안에 들어갈 수 있다는 것이다 !

function HorizontalRule({ show }) {
  if (show) {
    const theme = use(ThemeContext);
    return <hr className={theme} />;
  }
  return false;
}

정리

아직 공식 출시되지 않은 React 19에서 새로 나오게 될 Client Side Hook들에 대하여 알아보았다. 아직 실험기능들이라 정식 출시때는 조금씩 바뀔 수도 있겠지만 나오게 된다면 모두 유용하게 쓸 수 있는 Hook들임은 명확한 것 같다 !

profile
프론트엔드 개발자 🧑🏻‍💻 https://until.blog/@love

0개의 댓글