context란?
Context는 React 컴포넌트 트리 안에서 데이터를 전역적으로 공유할 수 있게 해주는 API다. 부모 컴포넌트에서 멀리 떨어진 자식 컴포넌트로 props를 일일이 전달하는 “props 드릴링” 문제를 해결해준다.
// UserContext.js - Context 생성하기
import { createContext, useState } from "react";
// 1. Context 생성
export const UserContext = createContext(null);
// 2. Provider 컴포넌트 만들기
export function UserProvider({ children }) {
const [user, setUser] = useState(null);
const login = (userData) => {
setUser(userData);
};
const logout = () => {
setUser(null);
};
// 공유할 값을 value에 넣는다
//.Provider 를 붙이는건 이제 사라짐
return <UserContext value=>{children}</UserContext>;
}
Context 사용하기
// App.js - 앱 최상위에 Provider 배치
import { UserProvider } from "./UserContext";
import Dashboard from "./Dashboard";
function App() {
return (
<UserProvider>
<div className="app">
<h1>우리 앱</h1>
<Dashboard />
</div>
</UserProvider>
);
}
// Dashboard.js - 중간 컴포넌트 (props 전달 안 해도 됨)
function Dashboard() {
return (
<div className="dashboard">
<h2>대시보드</h2>
<UserProfile />
</div>
);
}
// UserProfile.js - Context 값 사용하기
import { useContext } from "react";
import { UserContext } from "./UserContext";
function UserProfile() {
// 3. Context 값 꺼내 쓰기
const { user, logout } = useContext(UserContext);
if (!user) {
return <div>로그인 해주세요!</div>;
}
return (
<div>
<h3>안녕하세요, {user.name}님!</h3>
<button onClick={logout}>로그아웃</button>
</div>
);
}
Context 사용 시 주의사항
- 성능 이슈: Context가 변경되면 모든 소비자 컴포넌트가 리렌더링된다
- 남용 금지: 전역 상태 관리가 필요한 경우에만 사용하자
- 최적화: 자주 변경되는 데이터와 잘 변경되지 않는 데이터를 분리하면 좋다
실제 사용 사례
- 테마 (다크모드/라이트모드)
- 로그인한 사용자 정보
- 언어 설정(다국어 지원)
- UI 상태 (사이드바 열림/닫힘)
리액트 19 버전의 주요 변경점
리액트 19에서는 여러 중요한 변경사항이 도입되었다:
- 새로운 훅 ‘use’ Promise나 Context를 직접 소비할 수 있는 새 훅
function Avatar() {
const user = use(UserContext); // useContext 대신 use로 간단하게
const avatarData = use(fetchAvatar(user.id)); // 비동기 데이터도 바로 사용
return <img src={avatarData.url} />;
}
// 기존 방식 (React 18 이하)
function UserProfile() {
const { user, logout } = useContext(UserContext);
// ...
}
// 새로운 방식 (React 19)
function UserProfile() {
const { user, logout } = use(UserContext); // useContext보다 더 간결해짐
// ...
}
- Context 성능 개선
- React 19에서는 Context 소비자(consumer) 컴포넌트의 리렌더링 최적화가 개선되다.
- Context가 변경되어도 실제로 사용하는 값이 변경되지 않으면 리렌더링을 방지하는 최적화가 자동으로 적용
- Context와 Suspense 통합 강화
- Context와 Suspense를 함께 사용할 때 로딩 상태 처리가 더 자연스러워졌다
- Context 값이 로딩 중일 때 Suspense 경계에서 자동으로 대기하도록 개선되었다
- 서버 컴포넌트와의 호환성 향상
- 서버 컴포넌트에서 Context 제공자(Provider)를 사용하는 방법이 개선되었다
- 클라이언트와 서버 간의 Context 값 전달이 더 효율적으로 이루어진다
- Context는 리액트 19에서 ‘use’ 훅의 도입으로 더 간결하고 직관적으로 사용할 수 있게 되었으며, 전반적인 성능과 개발자 경험이 향상되었다!