Bird
Raised Fist0
Reactframework~5 mins

Context best practices in React

Choose your learning style10 modes available
Introduction

Context helps share data easily across many parts of a React app without passing props everywhere.

When many components need the same data, like user info or theme settings.
To avoid passing props through many layers of components.
When you want to keep global state simple and easy to access.
To share settings like language or color mode across the app.
When you want to avoid prop drilling that makes code messy.
Syntax
React
import React, { createContext, useContext, useState } from 'react';

const MyContext = createContext(null);

function MyProvider({ children }) {
  const [value, setValue] = useState(null);

  return (
    <MyContext.Provider value={{ value, setValue }}>
      {children}
    </MyContext.Provider>
  );
}

function MyComponent() {
  const context = useContext(MyContext);
  // use context.value or context.setValue
}

Always create context outside components to avoid recreating it on every render.

Use a Provider to wrap components that need access to the context data.

Examples
Creates a theme context with default 'light' and provides 'dark' to children.
React
const ThemeContext = createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}
Reads the current theme from context and shows it.
React
function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div>The current theme is {theme}</div>;
}
Provides user data and a way to update it to all children.
React
const UserContext = createContext(null);

function UserProvider({ children }) {
  const [user, setUser] = useState(null);
  return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;
}
Sample Program

This example shows a language context that shares the current language and a way to change it. The LanguageSwitcher component reads and updates the language using context.

React
import React, { createContext, useContext, useState } from 'react';

const LanguageContext = createContext('English');

function LanguageProvider({ children }) {
  const [language, setLanguage] = useState('English');

  return (
    <LanguageContext.Provider value={{ language, setLanguage }}>
      {children}
    </LanguageContext.Provider>
  );
}

function LanguageSwitcher() {
  const { language, setLanguage } = useContext(LanguageContext);

  return (
    <div>
      <p>Current language: {language}</p>
      <button onClick={() => setLanguage('Spanish')}>Switch to Spanish</button>
      <button onClick={() => setLanguage('English')}>Switch to English</button>
    </div>
  );
}

export default function App() {
  return (
    <LanguageProvider>
      <LanguageSwitcher />
    </LanguageProvider>
  );
}
OutputSuccess
Important Notes

Keep context values simple to avoid unnecessary re-renders.

Do not put large objects or functions in context unless needed.

Use multiple contexts if you have different kinds of data to share.

Summary

Context helps share data without passing props through many layers.

Wrap components with a Provider to give them access to context data.

Use useContext hook inside components to read or update context values.

Practice

(1/5)
1. What is the main purpose of React Context?
easy
A. To handle routing between pages
B. To style components globally
C. To manage component local state only
D. To share data between components without passing props manually

Solution

  1. Step 1: Understand React Context role

    React Context allows sharing data across many components without passing props at every level.
  2. Step 2: Compare with other options

    Styling, local state, and routing are handled by other React features or libraries, not Context.
  3. Final Answer:

    To share data between components without passing props manually -> Option D
  4. Quick Check:

    Context shares data without prop drilling [OK]
Hint: Context shares data without passing props repeatedly [OK]
Common Mistakes:
  • Confusing Context with styling or routing
  • Thinking Context manages only local state
  • Assuming Context replaces all state management
2. Which of the following is the correct way to create a Context in React?
easy
A. const MyContext = new Context();
B. const MyContext = createContext();
C. const MyContext = React.createContext();
D. const MyContext = React.useContext();

Solution

  1. Step 1: Recall Context creation syntax

    React Context is created using React.createContext() function.
  2. Step 2: Check other options

    A uses invalid constructor, B misses React prefix, D calls a hook instead of creating context.
  3. Final Answer:

    const MyContext = React.createContext(); -> Option C
  4. Quick Check:

    Use React.createContext() to create context [OK]
Hint: Create context with React.createContext() [OK]
Common Mistakes:
  • Omitting React prefix
  • Using new keyword incorrectly
  • Confusing useContext hook with createContext
3. Given this code snippet, what will be logged to the console?
const ThemeContext = React.createContext('light');

function DisplayTheme() {
  const theme = React.useContext(ThemeContext);
  console.log(theme);
  return <div>Current theme: {theme}</div>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <DisplayTheme />
    </ThemeContext.Provider>
  );
}
medium
A. "dark"
B. "light"
C. undefined
D. Error: useContext called outside Provider

Solution

  1. Step 1: Identify Provider value

    The ThemeContext.Provider wraps DisplayTheme with value "dark".
  2. Step 2: Understand useContext behavior

    useContext reads the nearest Provider value, so theme is "dark" inside DisplayTheme.
  3. Final Answer:

    "dark" -> Option A
  4. Quick Check:

    useContext reads Provider value, not default [OK]
Hint: useContext reads nearest Provider value, not default [OK]
Common Mistakes:
  • Assuming default value is used despite Provider
  • Thinking useContext returns undefined without explicit value
  • Confusing useContext with useState
4. What is wrong with this React Context usage?
const UserContext = React.createContext();

function Profile() {
  const user = React.useContext(UserContext);
  return <div>User: {user.name}</div>;
}

function App() {
  return <Profile />;
}
medium
A. UserContext.Provider is missing, so user is undefined causing error
B. useContext hook is used incorrectly inside Profile
C. React.createContext() requires a default value
D. Profile component should not access context directly

Solution

  1. Step 1: Check for Provider wrapping

    App renders Profile without wrapping it in UserContext.Provider, so context value is undefined.
  2. Step 2: Understand consequence in Profile

    Accessing user.name when user is undefined causes runtime error.
  3. Final Answer:

    UserContext.Provider is missing, so user is undefined causing error -> Option A
  4. Quick Check:

    Missing Provider means context value is undefined [OK]
Hint: Always wrap consumers with Provider to avoid undefined context [OK]
Common Mistakes:
  • Thinking createContext must have default value
  • Believing useContext usage is incorrect here
  • Assuming components can't access context directly
5. You want to update a theme value shared via Context from a nested component. Which is the best practice to enable this?
hard
A. Use useState inside the nested component to update theme locally
B. Pass a setter function in the Context value and call it inside the nested component
C. Create a new Context inside the nested component to override theme
D. Modify the Context object directly without Provider

Solution

  1. Step 1: Understand Context update pattern

    To update shared data, pass a setter function (like from useState) in Context value.
  2. Step 2: Evaluate other options

    Using local useState won't update shared theme; creating new Context breaks sharing; modifying Context object directly is invalid.
  3. Final Answer:

    Pass a setter function in the Context value and call it inside the nested component -> Option B
  4. Quick Check:

    Pass setter in Context to update shared state [OK]
Hint: Pass setter function via Context to update shared state [OK]
Common Mistakes:
  • Trying to update Context value directly
  • Using local state instead of shared state
  • Creating multiple Contexts unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard