0Pricing
React Native Academy · 강의

컨텍스트 만들고 제공하기

createContext로 React 컨텍스트를 만들고 컴포넌트 트리를 해당 Provider로 감싸며 모든 하위 컴포넌트가 읽을 수 있는 초기값을 전달합니다.

컨텍스트 만들고 제공하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Prop Drilling Problem

Prop drilling occurs when data needs to pass through many layers of components that do not use it themselves — they only pass it down to their children. For example, a user's authentication status might need to reach a deeply nested profile icon component, requiring it to be threaded through five intermediate components. The Context API solves this.

What is the Context API?

React's Context API lets you create a data channel that any component in the tree can subscribe to, regardless of how deeply nested it is. A Provider component supplies the value, and any descendant can read it with the useContext hook — no props required. It is built into React with no extra library needed.

Creating a Context with createContext

Call React.createContext(defaultValue) to create a context object. The defaultValue is only used when a component reads the context but has no matching Provider above it in the tree. In practice you almost always provide a value via the Provider, so the default is mainly used in tests.

import { createContext } from 'react';

// Create the context with a default value
export const ThemeContext = createContext({
  theme: 'light',
  toggleTheme: () => {},
});

The Context Provider Component

Every context object comes with a .Provider component. Wrap the part of your component tree that needs access to the context with ThemeContext.Provider. Pass the current value via the value prop. All descendants of the Provider can now read this value.

import { ThemeContext } from './ThemeContext';

function App() {
  const [theme, setTheme] = useState('light');

  const value = {
    theme,
    toggleTheme: () => setTheme(t => t === 'light' ? 'dark' : 'light'),
  };

  return (
    <ThemeContext.Provider value={value}>
      <NavigationContainer>
        <MainStack />
      </NavigationContainer>
    </ThemeContext.Provider>
  );
}

The Context Value Can Be Anything

The value you pass to the Provider can be any JavaScript value: a string, number, object, array, or function. In practice it is almost always an object that bundles both the current state and the functions to update it, keeping related data and behavior together.

// Simple string context
export const LanguageContext = createContext('en');

// Complex object context (more common)
export const UserContext = createContext({
  user: null,
  isAuthenticated: false,
  login: () => {},
  logout: () => {},
});

Building a Reusable Context Provider

A common pattern is creating a separate Provider component that encapsulates the state and updater functions. Export both the context and the provider from the same file. This keeps all the context logic in one place and makes the provider easy to compose with other providers in the app root.

import { createContext, useState } from 'react';

export const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  const login = (userData) => setUser(userData);
  const logout = () => setUser(null);

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

Using the Provider in App.js

Wrap your app (or the subtree that needs the context) with the Provider component. Place global providers near the top of the tree — usually wrapping the navigation container. You can stack multiple providers and they will all be available to their descendants.

import { AuthProvider } from './context/AuthContext';
import { ThemeProvider } from './context/ThemeContext';

export default function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <NavigationContainer>
          <MainStack />
        </NavigationContainer>
      </AuthProvider>
    </ThemeProvider>
  );
}

Multiple Contexts in the Same App

You can have as many contexts as needed. Common real-world contexts include: AuthContext for the logged-in user, ThemeContext for color scheme, CartContext for e-commerce, NotificationContext for push notification state. Keep each context focused on one concern to avoid re-render cascades when unrelated values change.

When Context Re-renders Consumers

Every time the Provider's value prop changes reference, all consumers re-render. If the value is an object literal created inline, it is a new reference on every parent render — even if the content is the same. You will learn to fix this with memoization in a later lesson, but understanding the trigger is the first step.

// Bad: new object on every render — all consumers re-render unnecessarily
<ThemeContext.Provider value={{ theme, toggleTheme }}>

// Better: memoize the value object
const value = useMemo(() => ({ theme, toggleTheme }), [theme]);

Nested Providers Override Values

If you nest two Providers of the same context, the inner Provider's value overrides the outer one for all descendants inside it. This lets you override context values for specific subtrees — useful for themes in a modal, or a different user scope in a section of the app.

// Outer provider: theme='light'
<ThemeContext.Provider value={{ theme: 'light' }}>
  <View>
    {/* Inner override for a modal: theme='dark' */}
    <ThemeContext.Provider value={{ theme: 'dark' }}>
      <Modal />
    </ThemeContext.Provider>
  </View>
</ThemeContext.Provider>

A Custom useAuth Hook

Encapsulate context access in a custom hook for a cleaner API. Export a useAuth hook that calls useContext(AuthContext). Add a guard to throw a helpful error if the hook is used outside of the AuthProvider, catching configuration mistakes early during development.

export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}

// Usage in any component
const { user, logout } = useAuth();

Quick Check

Test your understanding of creating and providing context from this lesson.

Lesson Recap

In this lesson you learned: createContext creates a context object with an optional default value, the Provider component supplies a value to all descendants, and encapsulate provider logic and updater functions in a dedicated Provider component. Next up we explore consuming context with the useContext hook.

자주 묻는 질문

“컨텍스트 만들고 제공하기” 강의는 무료인가요?

네 — “컨텍스트 만들고 제공하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“컨텍스트 만들고 제공하기”에서 뭘 배우나요?

createContext로 React 컨텍스트를 만들고 컴포넌트 트리를 해당 Provider로 감싸며 모든 하위 컴포넌트가 읽을 수 있는 초기값을 전달합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“컨텍스트 만들고 제공하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 컨텍스트 만들고 제공하기
  2. useContext로 컨텍스트 사용하기
  3. 다크 모드 전환이 있는 테마 컨텍스트
  4. 컨텍스트 성능 문제 피하기
← React Native Academy(으)로 돌아가기