React Native Academy · Leçon

Créer et fournir un contexte

Créez un contexte React avec createContext, enveloppez l’arbre des composants dans son Provider et transmettez une valeur initiale que tous les descendants peuvent lire.

Leçon 1 sur 413 étapes

Créer et fournir un contexte est une leçon React Native Academy gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage React Native Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours React Native Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Gratuit pour commencer

Apprends JavaScript avec un tuteur IA — gratuit

Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.

Cours
30
Leçons
120

Questions Fréquemment Posées

La leçon « Créer et fournir un contexte » est-elle gratuite ?

Oui — le texte complet de « Créer et fournir un contexte » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours React Native Academy, passe à CoddyKit PRO. Le cours React Native Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Créer et fournir un contexte » ?

Créez un contexte React avec createContext, enveloppez l’arbre des composants dans son Provider et transmettez une valeur initiale que tous les descendants peuvent lire. Tu pratiques React Native Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer React Native Academy ?

Aucune expérience préalable n'est requise. React Native Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Créer et fournir un contexte » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon React Native Academy ?

Oui. Chaque leçon React Native Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Créer et fournir un contexte
  2. Consommer un contexte avec useContext
  3. Un contexte de thème avec bascule du mode sombre
  4. Éviter les problèmes de performance liés au contexte
← Retour à React Native Academy