React v19 정리

Jeongbeen Lee·2025년 1월 5일

TechTalk

목록 보기
1/4
post-thumbnail

리액트 19버전의 새로운 점 중 몇가지를 소개하겠습니다. 다른 변경사항들은 공식블로그를 참고하시기 바랍니다.
React v19 blog

새로운 점

Actions

Data mutation 과 그에 따른 상태 업데이트를 간소화 하기 위해 도입된 개념이다.
새로 나온 useActionState, useOptimistic 과 같은 훅을 통해 대기 상태, 오류 처리, 낙관적 업데이트를 자동으로 관리할 수 있다.

// 기존 코드
function UpdateName({}) {
  const [name, setName] = useState("");
  const [error, setError] = useState(null);
  const [isPending, setIsPending] = useState(false);

  const handleSubmit = async () => {
    setIsPending(true);
    const error = await updateName(name);
    setIsPending(false);
    if (error) {
      setError(error);
      return;
    } 
    redirect("/path");
  };

  return (
    <div>
      <input value={name} onChange={(event) => setName(event.target.value)} />
      <button onClick={handleSubmit} disabled={isPending}>
        Update
      </button>
      {error && <p>{error}</p>}
    </div>
  );
}

이전까지는 입력영역마다 상태들을 선언하고 각각 제어해야 했다.

useActionState

const [error, submitAction, isPending] = useActionState(
  async (previousState, newName) => {
    const error = await updateName(newName);
    if (error) {
      // You can return any result of the action.
      // Here, we return only the error.
      return error;
    }

    // handle success
    return null;
  },
  null,
);

useActionState 를 사용하면 대기 상태, 에러 처리를 하나의 변수로 처리할 수 있게 해준다.

React DOM: <form>Actions 와 useFormStatus

먼저 <form>, <input>, <button> 요소에 actionformAction 속성을 추가하여 action이 포함된 form을 자동으로 실행될 수 있게 되었다.

<form action={actionFunction}>

또한 useFormStatus를 사용하면 자식 컴포넌트에서 부모 form의 제출상태, action 함수 등을 조회할 수 있다.

import {useFormStatus} from 'react-dom';

function DesignButton() {
  const {pending} = useFormStatus();
  return <button type="submit" disabled={pending} />
}

useOptimistic

비동기 요청이 진행중일때 상태를 미리 업데이트하는 것을 낙관적 업데이트라고 한다.
useOptimistic 훅은 이것을 더 쉽게 해준다.

function ChangeName({currentName, onUpdateName}) {
  const [optimisticName, setOptimisticName] = useOptimistic(currentName);

  const submitAction = async formData => {
    const newName = formData.get("name");
    setOptimisticName(newName);
    const updatedName = await updateName(newName);
    onUpdateName(updatedName);
  };

  return (
    <form action={submitAction}>
      <p>Your name is: {optimisticName}</p>
      <p>
        <label>Change Name:</label>
        <input
          type="text"
          name="name"
          disabled={currentName !== optimisticName}
        />
      </p>
    </form>
  );
}

위 코드에서, useOptimisticupdateName 요청이 진행중일 때 렌더링을 진행한다. 업데이트가 끝나거나 에러가 발생했을 때, 자동으로 currentName 변수에 반영한다.

Server Component

RSC(React-Server-Component)는 Next.js 에서 지원하는 server component 유사한 기능을 지원하며 db 쿼리로 직접 데이터를 읽어올 수 있고 SSR(Server-Side-Rendering)과 SSG(Static-Site-Generation)을 가능하게 해준다. 이 기능은 리액트만을 이용해서 앱을 개발하길 원하는 사람에게 많은 도움을 줄 것으로 보인다.

2개의 댓글

comment-user-thumbnail
2025년 1월 6일

유익한 글 감사합니다🥔🌱

답글 달기
comment-user-thumbnail
2025년 1월 8일

잘 설명해주셔서 감사해요! 공식문서를 자주 볼게요! 하나씩 배워가고있어요! 스터디가 정말 도움이 많이 되는것같습니당^^~

답글 달기