React 19 RC에서 use 훅 사용해보기
배경
React 19 RC가 공개되면서 공식 문서에서 use 훅을 발견했다. 기존에는 데이터 fetching을 위해 useEffect + useState 조합이나 React Query 같은 라이브러리를 사용했는데, use 훅은 Promise를 직접 다룰 수 있다고 해서 테스트 프로젝트에 적용해봤다.
use 훅의 특징
가장 큰 차이점은 조건문 안에서도 사용 가능하다는 것이다. 기존 Hook 규칙의 예외케이스로 추가된 것으로 보인다.
function UserProfile({ userId }) {
const user = use(fetchUser(userId));
return <div>{user.name}</div>;
}
Promise가 pending 상태일 때는 자동으로 Suspense boundary로 throw되고, resolve되면 결과값을 반환한다. 에러 발생 시에는 Error Boundary로 전파된다.
Context와의 통합
Context도 use로 읽을 수 있다.
function Button() {
const theme = use(ThemeContext);
return <button className={theme.primary}>Click</button>;
}
조건문 안에서 Context를 읽을 수 있다는 게 실용적이었다.
function Component({ showTheme }) {
if (showTheme) {
const theme = use(ThemeContext);
return <div style={{ color: theme.color }}>Themed</div>;
}
return <div>Default</div>;
}
실전 적용 시 고려사항
Promise를 컴포넌트 내에서 생성하면 렌더링마다 새로운 Promise가 만들어져 무한 루프에 빠진다. Promise는 컴포넌트 외부나 useMemo로 메모이제이션해야 한다.
// 잘못된 사용
function Bad() {
const data = use(fetch('/api')); // 매 렌더링마다 새로운 fetch
}
// 올바른 사용
const dataPromise = fetch('/api');
function Good() {
const data = use(dataPromise);
}
정리
React 19는 아직 RC 단계지만, use 훅은 데이터 fetching 패턴을 단순화할 가능성이 보인다. 다만 프로덕션 적용은 정식 릴리즈 이후에 검토할 예정이다. 기존 React Query나 SWR 대비 어떤 장단점이 있는지는 더 사용해봐야 알 것 같다.