0Pricing
React Native Academy · درس

استهلاك Context باستخدام useContext

اقرأ قيم context داخل أي مكوّن متداخل باستخدام hook ‏useContext، متجنبًا الحاجة إلى تمرير props عبر المكوّنات الوسيطة.

استهلاك Context باستخدام useContext درس مجاني في React Native Academy على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في React Native Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة React Native Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Reading Context with useContext

The useContext(ContextObject) hook lets any function component subscribe to a context and read its current value. It replaces the older Consumer render prop pattern with a simple hook call. The component automatically re-renders whenever the context value changes.

import { useContext } from 'react';
import { ThemeContext } from '../context/ThemeContext';

function Header() {
  const { theme } = useContext(ThemeContext);

  return (
    <View style={{ backgroundColor: theme === 'dark' ? '#1a1a2e' : '#fff' }}>
      <Text>My App</Text>
    </View>
  );
}

No Prop Drilling Required

The main benefit of useContext is that the consuming component does not need to receive props from its parent. The Header component in the previous example can be anywhere in the tree — three levels deep, inside a modal, or in a completely different branch — and it still reads the same theme value directly from context.

// Without context: theme prop drills through App→Screen→Section→Card→Header
// With context: Header reads theme directly from context
function DeepComponent() {
  const { user } = useContext(AuthContext); // no props needed
  return <Text>Welcome, {user.name}</Text>;
}

Calling Actions from Context

Context can expose not just data but also functions that update the data. Call these functions directly from the consuming component without knowing where the state lives. The Provider handles the state update and all consumers that depend on the value re-render automatically.

function LogoutButton() {
  const { logout } = useContext(AuthContext);

  return (
    <Button title='Sign Out' onPress={logout} />
  );
}

Using Multiple Contexts in One Component

A component can consume multiple contexts by calling useContext multiple times with different context objects. Each call is independent — a change in ThemeContext only causes re-renders in ThemeContext consumers, not in AuthContext consumers (unless they also depend on ThemeContext).

function ProfileScreen() {
  const { user } = useContext(AuthContext);
  const { theme } = useContext(ThemeContext);

  return (
    <View style={styles[theme]}>
      <Text style={styles[theme + 'Text']}>
        {user.name}
      </Text>
    </View>
  );
}

Context Value is the Latest Render

useContext always gives you the most recent value provided by the nearest matching Provider. When the Provider re-renders with a new value, React propagates the update to all consumers immediately, even if intermediate components between the Provider and consumer did not re-render. This is one of the key advantages over passing props through potentially non-rendering intermediaries.

Creating a useAuth Custom Hook

Instead of importing and calling useContext(AuthContext) in every component, wrap it in a custom useAuth hook. This abstracts away the context object import, makes the calling code more readable, and lets you add error checks or derived values in one place.

// context/AuthContext.js
export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be inside AuthProvider');
  return ctx;
}

// In any component
function NavBar() {
  const { user, logout } = useAuth(); // clean and simple
  return <Text>{user.email}</Text>;
}

Guarding Routes with Context

A common pattern is to read auth state from context and conditionally render either the authenticated app stack or the login screen. The root navigator reads the user from AuthContext — when user is null it renders the auth screens, and when it is set it renders the main app screens.

function RootNavigator() {
  const { user } = useAuth();

  return (
    <NavigationContainer>
      {user ? <AppStack /> : <AuthStack />}
    </NavigationContainer>
  );
}

Conditional Rendering Based on Context

Components can use context values to make render decisions. A premium feature component checks the user's subscription tier from context and renders either the full feature or a paywall CTA. This logic lives in the consuming component, keeping the Provider generic and reusable.

function PremiumFeature({ children }) {
  const { user } = useAuth();
  const isPro = user?.subscription === 'pro';

  if (!isPro) {
    return <UpgradePrompt />;
  }

  return children;
}

Context in List Items

Context works inside FlatList renderItem components too. Each list item can read from context without props. Be mindful that if the context value changes, every visible list item will re-render — use React.memo and ensure the context value is stable (memoized) to mitigate the impact.

const CartItem = React.memo(({ item }) => {
  const { addToCart } = useContext(CartContext);

  return (
    <View style={styles.row}>
      <Text>{item.name}</Text>
      <Button title='Add' onPress={() => addToCart(item)} />
    </View>
  );
});

Context vs Props: When to Use Each

Use props for data that is naturally owned by the parent and directly relevant to the child's display. Use context for global or cross-cutting concerns: authentication, theme, language, cart state. Over-using context for local data makes components harder to understand and reuse in isolation, because their dependencies are implicit rather than explicit.

The useContext Return Value

useContext returns exactly the value passed to the nearest Provider's value prop. If no Provider is found above the component, it returns the default value given to createContext(). Destructure the returned object directly at the call site for cleaner, more readable code.

// Full value object
const themeContext = useContext(ThemeContext);
themeContext.theme; // 'light' or 'dark'

// Destructured (preferred)
const { theme, toggleTheme } = useContext(ThemeContext);

// From custom hook
const { user, login, logout } = useAuth();

Quick Check

Test your understanding of consuming context with useContext from this lesson.

Lesson Recap

In this lesson you learned: useContext(ContextObject) reads the nearest Provider's value without prop drilling, a component can consume multiple contexts by calling useContext multiple times, and wrapping useContext in a custom hook gives a clean API with error checking. Next up we build a theme context with a dark mode toggle.

الأسئلة الشائعة

هل درس «استهلاك Context باستخدام useContext» مجاني؟

نعم — نص درس «استهلاك Context باستخدام useContext» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة React Native Academy، انتقل إلى CoddyKit PRO. تتضمن دورة React Native Academy 4 دروس في المجموع.

ماذا ستتعلم في «استهلاك Context باستخدام useContext»؟

اقرأ قيم context داخل أي مكوّن متداخل باستخدام hook ‏useContext، متجنبًا الحاجة إلى تمرير props عبر المكوّنات الوسيطة. تتمرن على React Native Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ React Native Academy؟

لا تُشترط خبرة سابقة. React Native Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «استهلاك Context باستخدام useContext»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس React Native Academy هذا؟

نعم. كل درس في React Native Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. إنشاء Context وتوفيره
  2. استهلاك Context باستخدام useContext
  3. ‏Theme Context مع مفتاح الوضع الداكن
  4. تجنب مشكلات أداء Context
← العودة إلى React Native Academy