React 19 beta가 나왔습니다. 많은 사람의 기대를 모았던 React 19 stable 버전의 릴리즈도 조만간 코앞에 오긴 했나 봅니다. beta에는 React Server Components(RSC)와 Action 같은 새 기능, 그리고 몇 가지 개선사항이 들어 있습니다.
다른 기능들도 간단히 설명하기에는 부족한 부분이 있지만, RSC는 특히 짧게 소개하면 오해의 소지가 있을 것 같아 이 글에서는 다루지 않았어요. RSC는 앞서 쓴 React Server Components(RSC) 차근차근 이해하기에 자세히 정리했습니다.
beta를 설치하려면 버전을 직접 명시해야 합니다.
npm install react@beta react-dom@beta타입스크립트를 쓰려면 타입 패키지도 beta로 오버라이드해야 해요.
{
"devDependencies": {
"@types/react": "npm:types-react@beta",
"@types/react-dom": "npm:types-react-dom@beta"
},
"overrides": {
"@types/react": "npm:types-react@beta",
"@types/react-dom": "npm:types-react-dom@beta"
}
}transition이 async 함수를 받게 됐다
리액트 팀은 React 19 공식 글에서 Action을 "Async Transition을 사용하는 함수"로 정의했습니다. React 18까지는 transition에 비동기 함수를 쓸 수 없었고, 19 beta부터 async transition을 지원해요. 이제 사용자 인터랙션에 영향을 주지 않으면서 데이터 페칭 같은 비동기 작업을 더 효율적으로 처리할 수 있게 됐습니다.
Action 이전에는 데이터 페칭에 따른 상태 업데이트를 관리하는 코드가 복잡했습니다. 요청 중인지를 나타내는 isPending도 useState로 직접 켜고 꺼야 했어요.
// before Action
const UpdateName = ({ currentName }) => {
const [name, setName] = useState("");
const [newName, setNewName] = useState(currentName);
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const handleSubmit = async () => {
setIsPending(true);
setNewName(newName);
const { error } = await updateName(name);
setIsPending(false);
if (error) {
setError(error);
return;
}
redirect("/path");
};
return (
<div>
<p>Your name is {newName}</p>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
};리액트 팀은 이 복잡성을 Action으로 해결하려 했습니다. useOptimistic 훅을 쓰면 요청을 보내는 동안에도 사용자에게 바로 피드백을 보여 주는 낙관적 업데이트를 할 수 있어요.
요청이 실패하면 Error Boundary를 보여 주고, 낙관적 업데이트를 원래 값으로 자동으로 되돌립니다. <form>의 action prop과 <button>, <input>의 formAction prop에도 함수를 넘길 수 있게 됐습니다. action에 넘긴 함수는 기본으로 Action이 되고, 제출 뒤에는 폼이 자동으로 리셋돼요.
Action은 요청이 시작될 때 pending 상태를 켜고, 마지막 상태 업데이트가 커밋되면 자동으로 되돌립니다. useTransition이 돌려주는 startTransition에 async 함수를 넘기면 isPending을 따로 관리하지 않아도 돼요.
// Using pending state from Actions
const UpdateName = ({ currentName }) => {
const [name, setName] = useState("");
const [newName, setNewName] = useState(currentName);
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const handleSubmit = async () => {
startTransition(async () => {
setNewName(newName);
const { error } = await updateName(name);
if (error) {
setError(error);
return;
}
redirect("/path");
});
};
return (
<div>
<p>Your name is {newName}</p>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
};useFormState는 useActionState로 이름이 바뀌었다
useActionState는 기존 useFormState의 한계를 개선해 나온 훅입니다. Action의 일반적인 경우에 쓰고, 사용법은 useFormState와 크게 다르지 않아요. Canary 릴리스에서는 ReactDOM.useFormState였습니다. React 버전 정책 문서에 따르면 Canary는 React 저장소의 main 브랜치를 따라가는 사전 릴리스 채널이에요.
core PR에 따르면 useFormState라는 이름은 이 훅이 특정 form의 상태를 다룬다는 오해를 부를 수 있었습니다. 실제로는 넘긴 action의 마지막 결과를 돌려줄 뿐이라, pending 상태를 붙이면 form이 아니라 action의 pending 상태가 돼요. 이 PR은 반환값에 pending을 더하고 훅을 react 패키지로 옮겼습니다.
주의 깊게 볼 점은 useActionState가 특정 <form>과 묶여 있지 않다는 것입니다. 꼭 <form>과 함께 쓸 필요는 없다는 말이지, <form>과 같이 쓰면 여러 가지 이점이 있어요. useActionState 문서에 따르면 form 없이 쓸 때는 반환된 함수를 startTransition 안에서 부릅니다.
첫 번째 인자인 함수는 이전 상태와 form 데이터를 차례로 받고, 두 번째 인자는 초기 상태입니다. 반환값은 현재 상태, form의 action에 넘길 함수, isPending 세 가지예요.
const UseActionState = () => {
const [state, action, isPending] = useActionState(
async (_: string, formData: FormData) => {
const newName = await updateName(formData.get("name") as string);
return newName;
},
""
);
return (
<Form action={action} className="flex flex-col items-start">
<h1 className="pb-2">useActionState</h1>
{isPending ? <p>loading...</p> : <p>Your name is {state}</p>}
<input name="name" className="border border-black my-3" />
<Form.Button>Submit</Form.Button>
</Form>
);
};useFormStatus는 부모 form을 Context처럼 읽는다
디자인 시스템을 고려해 컴포넌트를 구성하면 props drilling 없이 상위 컴포넌트의 상태에 접근하는 경우가 많습니다. 보통 Context로 풀지만, <form>이라면 useFormStatus 훅으로 더 쉽게 풀 수 있습니다. 이 훅은 <form>이 Context provider인 것처럼 그 <form>의 상태를 읽어요.
useFormStatus는 react-dom에서 가져옵니다. useFormStatus 문서에 따르면 이 훅은 <form> 안에 렌더되는 컴포넌트에서 불러야 하고, 부모 <form>의 상태만 돌려줘요. 같은 컴포넌트가 렌더한 <form>의 상태는 읽지 못합니다.
import type { PropsWithChildren } from "react";
import { useFormStatus } from "react-dom";
const Button = ({ children }: PropsWithChildren) => {
const status = useFormStatus();
return (
<button
type="submit"
className={`py-3 px-2 bg-black text-white font-bold rounded ${
status.pending ? "opacity-65" : ""
}`}
disabled={status.pending}
>
{children}
</button>
);
};
export default Button;버튼을 <form> 아래 어디에 두든 status.pending을 읽을 수 있습니다. <form> 컴포넌트 깊이에 따른 props drilling은 크게 고민하지 않아도 돼요.
useOptimistic은 응답 전에 결과를 먼저 보여 준다
서버로 data mutation을 할 때는 네트워크 응답을 기다리는 동안 사용자 인터랙션이 화면에 반영되지 않습니다. React에서는 보통 낙관적 업데이트로 이 문제를 풉니다. 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>
);
}updateName 요청이 진행되는 동안에는 optimisticName이 먼저 렌더됩니다. React 19 공식 글에 따르면 요청이 끝나거나 실패하면 optimisticName은 자동으로 currentName 값으로 돌아가요.
forwardRef와 Context.Provider가 deprecated 예정이 됐다
함수 컴포넌트가 이제 props로 ref를 받을 수 있습니다.
function MyInput({ placeholder, ref }) {
return <input placeholder={placeholder} ref={ref} />;
}
//...
<MyInput ref={ref} />;forwardRef로 ref를 전달할 이유가 없어져서 향후 버전에서는 deprecated될 예정이에요. 공식 글은 컴포넌트를 새 ref prop 방식으로 자동으로 바꿔 주는 codemod도 내겠다고 밝혔습니다.
Context도 <Context.Provider> 대신 <Context>를 Provider로 렌더할 수 있습니다.
const ThemeContext = createContext("");
function App({ children }) {
return <ThemeContext value="dark">{children}</ThemeContext>;
}그래서 <Context.Provider>도 곧 deprecated될 예정입니다.
use는 조건문 안에서도 Promise를 읽는다
Context나 Promise 같은 리소스 값을 읽는 API인 use가 React 19 beta에 들어왔습니다. 개인적으로 이전부터 관심이 있었는데, 아주 재밌고 흥미로운 훅이기 때문이었어요.
use가 나온 배경에는 서버 컴포넌트가 있습니다. 서버 컴포넌트에 한해 async 컴포넌트를 만들 수 있게 됐지만, 클라이언트 컴포넌트는 컴포넌트 안에서 바로 비동기 처리를 하지 못하고 useEffect 훅 안에서 해야 했어요.
RFC 문서는 기술적 한계 때문에 클라이언트에서 도는 컴포넌트에서는 await를 지원하지 않는다고 설명합니다. 리액트 팀은 이 어려움을 풀려고 React만의 async/await 모델로 use를 만들었어요. async 함수 안에서만 await를 쓸 수 있는 것처럼, use도 React 컴포넌트와 훅 안에서만 쓸 수 있습니다.
// read context
function Component() {
const context = useContext(SomethingContext);
// const context = use(SomethingContext); // same
// …
}
// read promise
function ItemsPage() {
const somePromise = getData();
return (
<Suspense fallback={<p>loading...</p>}>
<Items resource={somePromise} />
</Suspense>
);
}
function Items({ resource }) {
const data = use(resource);
return data.map((item) => <Item key={item.id} item={item} />);
}위 예제에서 getData()로 Promise를 만드는 ItemsPage가 서버 컴포넌트라면 괜찮습니다. 클라이언트 컴포넌트의 렌더 중에 만든 Promise를 use에 넘기면 렌더할 때마다 Promise가 새로 만들어져 Suspense fallback이 되풀이돼요. use 문서는 이벤트 핸들러나 서버 컴포넌트처럼 렌더 전에 만든 Promise를 넘기거나, Promise를 캐시해 같은 인스턴스를 다시 쓰라고 안내합니다.
use는 다른 훅과 달리 조건문, 블록, 루프 안에서도 부를 수 있습니다. 로직을 별도 컴포넌트로 떼어 내지 않고도 데이터 로딩을 조건부로 기다릴 수 있어요. 아래 예제는 같은 RFC 문서에 있는 코드입니다. 렌더 중에 fetchNote(id)를 부르므로, 클라이언트 컴포넌트라면 fetchNote와 fetchNoteAuthor가 캐시된 Promise를 돌려줘야 해요.
function Note({ id, shouldIncludeAuthor }) {
const note = use(fetchNote(id));
let byline = null;
if (shouldIncludeAuthor) {
const author = use(fetchNoteAuthor(note.authorId));
byline = <h2>{author.displayName}</h2>;
}
return (
<div>
<h1>{note.title}</h1>
{byline}
<section>{note.body}</section>
</div>
);
}use에 넘긴 Promise는 reject될 수 있고, reject된 Promise를 처리하는 방법은 2가지입니다. use는 Suspense와 맞물리려고 안에서 throw하기 때문에 try-catch 블록 안에서 부를 수 없어요. try-catch 대신 Promise의 catch 메서드로 대체 값을 주거나, 컴포넌트를 Error Boundary로 감싸야 합니다.
첫 번째 방법인 catch에서 대체 값을 돌려주면, Promise가 reject돼도 Message는 그 값을 받습니다. 아래 App도 렌더 중에 Promise를 만들기 때문에 서버 컴포넌트라고 보고 읽어야 해요.
import { Suspense } from "react";
import { Message } from "./message.js";
export default function App() {
const messagePromise = new Promise((resolve, reject) => {
reject();
}).catch(() => {
return "no new message found.";
});
return (
<Suspense fallback={<p>waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}두 번째 방법에서는 reject된 에러가 가장 가까운 Error Boundary로 전파돼 fallback이 보입니다. 아래 예제의 ErrorBoundary는 react-error-boundary 패키지에서 가져왔어요.
import { use, Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";
export function MessageContainer({ messagePromise }) {
return (
<ErrorBoundary fallback={<p>⚠️Something went wrong</p>}>
<Suspense fallback={<p>⌛Downloading message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}
function Message({ messagePromise }) {
const content = use(messagePromise);
return <p>Here is the message: {content}</p>;
}cache는 beta에 들어오지 않았다
같은 RFC는 use가 suspend하기 전에 마이크로태스크가 끝나기를 기다리는 방식이 데이터 요청이 캐시돼 있을 때만 통한다고 설명합니다. cache가 use를 어떻게 보완하는지도 이 RFC에 자세히 나와 있어요.
React 19 beta에 cache API도 포함될지 궁금했는데, 아쉽게도 들어오지 않았습니다. use와 cache는 서로 연관이 있어서, beta에는 빠졌어도 19가 정식으로 릴리즈되면 cache API도 같이 나올 거라고 봤습니다.