react19 바뀐점
React 19로 업그레이드 명령어 (현재 19버전이 아닐 시)
npm install --save-exact react@^19.0.0 react-dom@^19.0.0
React 19 주요 변경점 React 19는 여러 혁신적인 기능과 개선 사항을 도입했다. 이 버전에서 가장 중요한 변화들을 알아보자.
- 새로운 ‘use’ 훅 Promise와 Context를 직접 사용할 수 있는 새로운 훅이 추가되었다. 또한 .provider도 사라짐
import { use } from "react";
function UserProfile() {
// Context 사용
const { user } = use(UserContext);
// 비동기 데이터 직접 사용
const userData = use(fetchUserData(user.id));
return <div>안녕하세요, {userData.name}님!</div>;
}
/ 2. Document Metadata API 컴포넌트에서 직접 타이틀과 메타 태그를 관리할 수 있다.
function ProductPage({ product }) {
return (
<>
<title>{product.name}</title>
<meta name="description" content={product.description} />
<h1>{product.name}</h1>
{/* 내용... */}
</>
);
}
- Actions API (폼 처리) 서버 액션과 함께 사용하여 폼 제출을 쉽게 처리할 수 있다.
function SignupForm() {
async function handleSubmit(formData) {
// formData에서 직접 값 추출
const username = formData.get("username");
const email = formData.get("email");
// 서버에 데이터 전송
await createUser({ username, email });
}
return (
<form action={handleSubmit}>
<input name="username" placeholder="사용자 이름" />
<input name="email" type="email" placeholder="이메일" />
<button type="submit">가입하기</button>
</form>
);
}
- 자동 메모이제이션 일부 상황에서 React.memo, useMemo, useCallback 없이도 자동 최적화가 적용된다.
// 이전에는 최적화를 위해 명시적으로 메모이제이션 필요
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
// React 19에서는 자동으로 최적화되는 경우가 많아짐
const value = computeExpensiveValue(a, b); // 불필요한 재계산 방지
- React 캐시 API 데이터 페칭과 계산 결과를 캐싱할 수 있는 내장 API가 추가되었다.
import { cache } from "react";
// 동일한 인자로 호출하면 캐시된 결과 반환
const fetchUser = cache(async (userId) => {
const response = await fetch(`/api/users/${userId}`);
return response.json();
});
function UserProfile({ userId }) {
const user = use(fetchUser(userId));
return <div>{user.name}</div>;
}
- 서버 컴포넌트 개선 완전한 서버 컴포넌트 지원으로 클라이언트와 서버 코드를 자연스럽게 혼합할 수 있다.
// 서버 컴포넌트 (데이터베이스 직접 접근 가능)
async function UserList() {
const users = await db.users.findMany();
return (
<div>
<h1>사용자 목록</h1>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} - <UserActions user={user} />
</li>
))}
</ul>
</div>
);
}
// 클라이언트 컴포넌트 (인터랙티브 요소 포함)
("use client");
function UserActions({ user }) {
return (
<button onClick={() => alert(`${user.name}님을 선택했습니다!`)}>
선택
</button>
);
}
- Suspense 개선 데이터 로딩, 코드 스플리팅, 이미지 로딩 등을 더 효과적으로 처리할 수 있다.
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<UserDashboard />
</Suspense>
);
}
- 에러 처리 개선 새로운
컴포넌트로 더 간편한 에러 처리가 가능해졌다.
function App() {
return (
<ErrorBoundary fallback={<ErrorMessage />}>
<UserProfile />
</ErrorBoundary>
);
}
-
성능 개선 전반적인 렌더링 성능이 향상되고, 자동 배칭(automatic batching)이 더욱 개선되었다.
-
Asset Loading API 이미지, 폰트, 스크립트 등 자산을 더 효율적으로 로드할 수 있다.
import { preload } from "react";
// 사용자가 버튼에 호버했을 때 미리 데이터 로드
function PreloadButton() {
return (
<button
onMouseEnter={() => preload("/api/data")}
onClick={() => navigate("/details")}
>
상세 정보 보기
</button>
);
}
React 19는 서버 컴포넌트, 자동 최적화, 개선된 데이터 로딩 등을 통해 개발자 경험을 크게 향상시키고, 애플리케이션의 성능과 유지보수성을 개선했다. 이러한 변화들은 React 생태계의 미래 방향을 제시하고 있다!