0Pricing
React Native Academy · Урок

Устранение проблем производительности контекста

Выявляйте ненужные повторные рендеринги, вызванные изменениями значения контекста, разделяйте контекст между несколькими провайдерами и мемоизируйте значения контекста для оптимизации производительности.

«Устранение проблем производительности контекста» — бесплатный урок React Native Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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 use

Separating 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 Provider

Selector 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) и разблокировать остальной курс React Native Academy, подпишись на CoddyKit PRO. Курс React Native Academy содержит 4 уроков всего.

Чему я научусь в уроке «Устранение проблем производительности контекста»?

Выявляйте ненужные повторные рендеринги, вызванные изменениями значения контекста, разделяйте контекст между несколькими провайдерами и мемоизируйте значения контекста для оптимизации производительно… Ты практикуешь React Native Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать React Native Academy?

Предыдущий опыт не требуется. React Native Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Устранение проблем производительности контекста»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке React Native Academy?

Да. Каждый урок React Native Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Создание и предоставление контекста
  2. Использование контекста с useContext
  3. Контекст темы и переключатель тёмного режима
  4. Устранение проблем производительности контекста
← Назад к React Native Academy