Bird
Raised Fist0
Reactframework~10 mins

Context best practices in React - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Context best practices
Create Context
↓
Provide Context Value
↓
Consume Context in Child
↓
Use Context Value
↓
Update Context Value (optional)
↓
Re-render Consumers
This flow shows how React Context is created, provided, consumed, and optionally updated to share data across components.
Execution Sample
React
const ThemeContext = React.createContext('light');

function App() {
  const [theme, setTheme] = React.useState('light');
  return (
    <ThemeContext.Provider value={{theme, setTheme}}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}
This code creates a ThemeContext, provides a theme state and updater, and passes it down to child components.
Execution Table
StepActionContext ValueComponent RenderedEffect
1Create ThemeContextdefault: 'light'NoneContext object ready
2App renders with theme='light'{theme: 'light', setTheme: fn}AppProvider wraps children
3Toolbar renders inside Provider{theme: 'light', setTheme: fn}ToolbarToolbar can consume context
4User triggers theme change{theme: 'dark', setTheme: fn}App re-rendersContext value updated
5Toolbar re-renders with new context{theme: 'dark', setTheme: fn}ToolbarUI updates to dark theme
6No more updates{theme: 'dark', setTheme: fn}StableRendering stops
💡 Rendering stops when no state or context changes occur
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
theme'light''light''light''light''dark''dark'
setThemefunctionfunctionfunctionfunctionfunctionfunction
Context Value{theme:'light', setTheme}{theme:'light', setTheme}{theme:'light', setTheme}{theme:'light', setTheme}{theme:'dark', setTheme}{theme:'dark', setTheme}
Key Moments - 3 Insights
Why do we wrap child components with the Provider?
The Provider passes the context value down the tree. Without it, children get the default context value (see Step 2 and 3 in execution_table).
What happens when the context value changes?
All components consuming that context re-render with the new value (see Steps 4 and 5 in execution_table).
Can we update context value from a child component?
Yes, if the updater function is provided in context (like setTheme), children can call it to update context (Step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the context value when Toolbar first renders?
Adefault 'light' string
B{theme: 'dark', setTheme: fn}
C{theme: 'light', setTheme: fn}
Dundefined
💡 Hint
Check Step 3 in the execution_table where Toolbar renders inside Provider
At which step does the theme change from 'light' to 'dark'?
AStep 4
BStep 5
CStep 2
DStep 6
💡 Hint
Look at the 'Context Value' column in execution_table for theme updates
If we remove the Provider, what context value will Toolbar receive?
AThe last updated context value
BThe default context value
CAn error occurs
Dnull
💡 Hint
Recall Step 1 default context value and Step 3 Provider role
Concept Snapshot
React Context best practices:
- Create context with React.createContext(defaultValue)
- Wrap children with Provider passing value
- Consume context with useContext hook
- Provide updater functions in context to allow changes
- Avoid overusing context to prevent unnecessary re-renders
Full Transcript
This visual execution shows how React Context works step-by-step. First, a context is created with a default value. Then, the App component provides a context value including state and updater function. Child components like Toolbar consume this context to access shared data. When the user triggers a change, the context value updates, causing consuming components to re-render with new data. Wrapping children with Provider is essential to pass the current context value. Without it, children get the default value. Providing updater functions in context allows children to change shared state. This pattern helps share data like themes or user info across components cleanly and efficiently.

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