컨텍스트 성능 문제 피하기
컨텍스트 값 변경으로 발생하는 불필요한 재렌더링을 찾아내고, 컨텍스트를 여러 Provider로 나누며, 성능 최적화를 위해 컨텍스트 값을 메모이제이션합니다.
컨텍스트 성능 문제 피하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Context Re-Render Problem
When the Context Provider re-renders with a new value, every component that calls useContext for that context re-renders, regardless of whether the specific part of the value they use has changed. In large apps with many consumers this can cascade into significant performance problems.
Diagnosing Unnecessary Context Re-renders
Use the React DevTools Profiler to identify components that re-render too often. Record an interaction that should only affect one part of the UI, then inspect which components highlighted in the flame chart. If components that only read one piece of context re-render when an unrelated piece changes, you have a performance problem.
The Inline Object Anti-Pattern
The most common source of unnecessary context re-renders is creating the value object inline in JSX. This creates a new object reference on every render of the Provider, which React treats as a changed value — even when the contents are identical — triggering a re-render cascade in all consumers.
// Bad: new object on every render
<MyContext.Provider value={{ user, logout }}>
// Good: stable reference with useMemo
const value = useMemo(() => ({ user, logout }), [user, logout]);
<MyContext.Provider value={value}>Memoizing Context Values with useMemo
Wrap the context value object in useMemo inside the Provider. React will only create a new object (and thus notify consumers) when one of the listed dependencies changes. This is the simplest and most impactful fix for context performance issues.
function CartProvider({ children }) {
const [items, setItems] = useState([]);
const addItem = useCallback((item) => {
setItems((prev) => [...prev, item]);
}, []);
const value = useMemo(() => ({
items,
addItem,
total: items.reduce((sum, i) => sum + i.price, 0),
}), [items, addItem]);
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}Splitting Contexts for Independent Concerns
If your context holds both frequently changing values (e.g., cart item count) and rarely changing values (e.g., user profile), consumers that only need the stable data are forced to re-render whenever the volatile data changes. The fix is to split the context into two separate providers — one for each concern.
// Instead of one big UserContext:
export const UserDataContext = createContext(null); // changes rarely
export const UserActionsContext = createContext(null); // changes rarely
export const CartItemsContext = createContext([]); // changes often
// Consumers only subscribe to what they useSeparating State from Dispatch
A proven pattern is to split context into a state context and a dispatch context. Dispatch functions never change (useCallback or useReducer dispatch are stable), so components that only dispatch actions are never re-rendered by state changes. Only components reading state re-render when state changes.
export const AppStateContext = createContext(null);
export const AppDispatchContext = createContext(null);
function AppProvider({ children }) {
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppStateContext.Provider value={state}>
<AppDispatchContext.Provider value={dispatch}>
{children}
</AppDispatchContext.Provider>
</AppStateContext.Provider>
);
}React.memo Does NOT Help Context Consumers
A common mistake is wrapping context consumers in React.memo thinking it will prevent re-renders caused by context changes. It does not — React.memo only compares props, not context subscriptions. A component consuming context will always re-render when the context value changes, regardless of React.memo.
// React.memo does NOT prevent context-driven re-renders
const MyComponent = React.memo(() => {
const { value } = useContext(MyContext);
// Still re-renders every time MyContext changes
return <Text>{value}</Text>;
});
// Solution: Split context or memoize the value in the ProviderSelector Pattern for Context
If you need granular subscriptions similar to Redux's useSelector, you can implement a simple selector pattern. A custom hook accepts a selector function and memoizes the selected value with useMemo. Re-renders only occur when the selected value changes, not the entire context.
function useCartTotal() {
const { items } = useContext(CartContext);
// Only recomputes when items changes
return useMemo(
() => items.reduce((sum, item) => sum + item.price, 0),
[items]
);
}
// Component only re-renders when the total number changes
function CartBadge() {
const total = useCartTotal();
return <Text>${total.toFixed(2)}</Text>;
}Keeping Providers Lightweight
The Provider component itself should be as simple as possible. Move expensive computations out of the Provider render into useMemo or into the reducer. Avoid fetching data, running heavy transformations, or creating large objects inline inside the Provider JSX on every render.
Composition Over One Giant Context
Avoid the temptation to put all global app state in a single context. A better architecture uses many small, focused contexts: AuthContext for auth, ThemeContext for colors, CartContext for cart, NotificationContext for alerts. Each context re-renders only its own consumers, keeping the surface area of each re-render small and predictable.
// Architecture with focused contexts
export default function App() {
return (
<AuthProvider>
<ThemeProvider>
<CartProvider>
<NotificationProvider>
<AppContent />
</NotificationProvider>
</CartProvider>
</ThemeProvider>
</AuthProvider>
);
}When to Consider Zustand or Redux
If context performance optimizations become too complex — or if you find yourself building an elaborate selector system — consider switching to Zustand or Redux Toolkit. These libraries offer fine-grained subscriptions out of the box and are designed for large-scale state management. Context remains ideal for simple global values like theme, auth, and preferences.
Quick Check
Test your understanding of avoiding context performance issues from this lesson.
Lesson Recap
In this lesson you learned: inline value objects in Provider JSX cause unnecessary re-renders — use useMemo to stabilize them, split large contexts into focused smaller contexts to limit re-render scope, and separate state and dispatch into two contexts so action-only components never re-render on state changes. Next up we explore the useEffect hook and dependency arrays for data fetching.
자주 묻는 질문
“컨텍스트 성능 문제 피하기” 강의는 무료인가요?
네 — “컨텍스트 성능 문제 피하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“컨텍스트 성능 문제 피하기”에서 뭘 배우나요?
컨텍스트 값 변경으로 발생하는 불필요한 재렌더링을 찾아내고, 컨텍스트를 여러 Provider로 나누며, 성능 최적화를 위해 컨텍스트 값을 메모이제이션합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“컨텍스트 성능 문제 피하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 컨텍스트 만들고 제공하기
- useContext로 컨텍스트 사용하기
- 다크 모드 전환이 있는 테마 컨텍스트
- 컨텍스트 성능 문제 피하기