logo by @sawaratsuki1004
React
v19.2
تعلم
مرجع
المجتمع
المدونة

هل هذه الصفحة مفيدة؟

في هذه الصفحة

  • Overview
  • Reference
  • createContext(defaultValue)
  • SomeContext.Provider
  • SomeContext.Consumer
  • Usage
  • Creating context
  • Importing and exporting context from a file
  • Troubleshooting
  • I can’t find a way to change the context value

    react@19.2

  • نظرة عامة
  • Hooks
    • useActionState
    • useCallback
    • useContext
    • useDebugValue
    • useDeferredValue
    • useEffect
    • useEffectEvent
    • useId
    • useImperativeHandle
    • useInsertionEffect
    • useLayoutEffect
    • useMemo
    • useOptimistic
    • useReducer
    • useRef
    • useState
    • useSyncExternalStore
    • useTransition
  • المكونات
    • <Fragment> (<>)
    • <Profiler>
    • <StrictMode>
    • <Suspense>
    • <Activity>
    • <ViewTransition> - هذه الميزة متاحة في أحدث إصدار Canary من React
  • APIs
    • act
    • addTransitionType - هذه الميزة متاحة في أحدث إصدار Canary من React
    • cache
    • cacheSignal
    • captureOwnerStack
    • createContext
    • lazy
    • memo
    • startTransition
    • use
    • experimental_taintObjectReference - هذه الميزة متاحة في أحدث إصدار تجريبي من React
    • experimental_taintUniqueValue - هذه الميزة متاحة في أحدث إصدار تجريبي من React
  • react-dom@19.2

  • Hooks
    • useFormStatus
  • المكونات (Components)
    • Common (e.g. <div>)
    • <form>
    • <input>
    • <option>
    • <progress>
    • <select>
    • <textarea>
    • <link>
    • <meta>
    • <script>
    • <style>
    • <title>
  • APIs
    • createPortal
    • flushSync
    • preconnect
    • prefetchDNS
    • preinit
    • preinitModule
    • preload
    • preloadModule
  • Client APIs
    • createRoot
    • hydrateRoot
  • Server APIs
    • renderToPipeableStream
    • renderToReadableStream
    • renderToStaticMarkup
    • renderToString
    • resume
    • resumeToPipeableStream
  • Static APIs
    • prerender
    • prerenderToNodeStream
    • resumeAndPrerender
    • resumeAndPrerenderToNodeStream
  • React Compiler

  • الإعدادات (Configuration)
    • compilationMode
    • gating
    • logger
    • panicThreshold
    • target
  • Directives
    • "use memo"
    • "use no memo"
  • تصريف المكتبات (Compiling Libraries)
  • React DevTools

  • React Performance tracks
  • eslint-plugin-react-hooks

  • Lints
    • exhaustive-deps
    • rules-of-hooks
    • component-hook-factories
    • config
    • error-boundaries
    • gating
    • globals
    • immutability
    • incompatible-library
    • preserve-manual-memoization
    • purity
    • refs
    • set-state-in-effect
    • set-state-in-render
    • static-components
    • unsupported-syntax
    • use-memo
  • قواعد React (Rules of React)

  • نظرة عامة (Overview)
    • Components و Hooks يجب أن تكون Pure
    • React تستدعي Components و Hooks
    • قواعد Hooks
  • React Server Components

  • Server Components
  • Server Functions
  • Directives
    • 'use client'
    • 'use server'
  • Legacy APIs

  • Legacy React APIs
    • Children
    • cloneElement
    • Component
    • createElement
    • createRef
    • forwardRef
    • isValidElement
    • PureComponent
مرجع API
APIs

createContext

createContext lets you create a context that components can provide or read.

const SomeContext = createContext(defaultValue)

  • Reference
    • createContext(defaultValue)
    • SomeContext.Provider
    • SomeContext.Consumer
  • Usage
    • Creating context
    • Importing and exporting context from a file
  • Troubleshooting
    • I can’t find a way to change the context value

Reference

createContext(defaultValue)

Call createContext outside of any components to create a context.

import { createContext } from 'react'; const ThemeContext = createContext('light');

See more examples below.

Parameters

  • defaultValue: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don’t have any meaningful default value, specify null. The default value is meant as a “last resort” fallback. It is static and never changes over time.

Returns

createContext returns a context object.

The context object itself does not hold any information. It represents which context other components read or provide. Typically, you will use SomeContext.Provider in components above to specify the context value, and call useContext(SomeContext) in components below to read it. The context object has a few properties:

  • SomeContext.Provider lets you provide the context value to components.
  • SomeContext.Consumer is an alternative and rarely used way to read the context value.

SomeContext.Provider

Wrap your components into a context provider to specify the value of this context for all components inside:

function App() { const [theme, setTheme] = useState('light'); // ... return ( <ThemeContext.Provider value={theme}> <Page /> </ThemeContext.Provider> ); }

Props

  • value: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling useContext(SomeContext) inside of the provider receives the value of the innermost corresponding context provider above it.

SomeContext.Consumer

Before useContext existed, there was an older way to read context:

function Button() { // 🟡 Legacy way (not recommended) return ( <ThemeContext.Consumer> {theme => ( <button className={theme} /> )} </ThemeContext.Consumer> ); }

Although this older way still works, but newly written code should read context with useContext() instead:

function Button() { // ✅ Recommended way const theme = useContext(ThemeContext); return <button className={theme} />; }

Props

  • children: A function. React will call the function you pass with the current context value determined by the same algorithm as useContext() does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context from the parent components changes.

Usage

Creating context

Context lets components pass information deep down without explicitly passing props.

Call createContext outside any components to create one or more contexts.

import { createContext } from 'react'; const ThemeContext = createContext('light'); const AuthContext = createContext(null);

createContext returns a context object. Components can read context by passing it to useContext():

function Button() { const theme = useContext(ThemeContext); // ... } function Profile() { const currentUser = useContext(AuthContext); // ... }

By default, the values they receive will be the default values you have specified when creating the contexts. However, by itself this isn’t useful because the default values never change.

Context is useful because you can provide other, dynamic values from your components:

function App() { const [theme, setTheme] = useState('dark'); const [currentUser, setCurrentUser] = useState({ name: 'Taylor' }); // ... return ( <ThemeContext.Provider value={theme}> <AuthContext.Provider value={currentUser}> <Page /> </AuthContext.Provider> </ThemeContext.Provider> ); }

Now the Page component and any components inside it, no matter how deep, will “see” the passed context values. If the passed context values change, React will re-render the components reading the context as well.

Read more about reading and providing context and see examples.


Importing and exporting context from a file

Often, components in different files will need access to the same context. This is why it’s common to declare contexts in a separate file. Then you can use the export statement to make context available for other files:

// Contexts.js import { createContext } from 'react'; export const ThemeContext = createContext('light'); export const AuthContext = createContext(null);

Components declared in other files can then use the import statement to read or provide this context:

// Button.js import { ThemeContext } from './Contexts.js'; function Button() { const theme = useContext(ThemeContext); // ... }

// App.js import { ThemeContext, AuthContext } from './Contexts.js'; function App() { // ... return ( <ThemeContext.Provider value={theme}> <AuthContext.Provider value={currentUser}> <Page /> </AuthContext.Provider> </ThemeContext.Provider> ); }

This works similar to importing and exporting components.


Troubleshooting

I can’t find a way to change the context value

Code like this specifies the default context value:

const ThemeContext = createContext('light');

This value never changes. React only uses this value as a fallback if it can’t find a matching provider above.

To make context change over time, add state and wrap components in a context provider.

السابقcaptureOwnerStack
التاليlazy

Copyright © Meta Platforms, Inc
no uwu plz
uwu?
Logo by@sawaratsuki1004
تعلم React
بداية سريعة
التثبيت
وصف واجهة المستخدم (UI)
إضافة التفاعلية
إدارة State
مخارج الطوارئ
مرجع API
React APIs
React DOM APIs
المجتمع
ميثاق السلوك
تعرف على الفريق
المساهمون في التوثيق
شكر وتقدير
المزيد
المدونة
React Native
الخصوصية
الشروط
const SomeContext = createContext(defaultValue)
import { createContext } from 'react';

const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
function Button() {
// 🟡 Legacy way (not recommended)
return (
<ThemeContext.Consumer>
{theme => (
<button className={theme} />
)}
</ThemeContext.Consumer>
);
}
function Button() {
// ✅ Recommended way
const theme = useContext(ThemeContext);
return <button className={theme} />;
}
import { createContext } from 'react';

const ThemeContext = createContext('light');
const AuthContext = createContext(null);
function Button() {
const theme = useContext(ThemeContext);
// ...
}

function Profile() {
const currentUser = useContext(AuthContext);
// ...
}
function App() {
const [theme, setTheme] = useState('dark');
const [currentUser, setCurrentUser] = useState({ name: 'Taylor' });

// ...

return (
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<Page />
</AuthContext.Provider>
</ThemeContext.Provider>
);
}
// Contexts.js
import { createContext } from 'react';

export const ThemeContext = createContext('light');
export const AuthContext = createContext(null);
// Button.js
import { ThemeContext } from './Contexts.js';

function Button() {
const theme = useContext(ThemeContext);
// ...
}
// App.js
import { ThemeContext, AuthContext } from './Contexts.js';

function App() {
// ...
return (
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<Page />
</AuthContext.Provider>
</ThemeContext.Provider>
);
}
const ThemeContext = createContext('light');