Bird
Raised Fist0
Reactframework~10 mins

Creating context in React - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - Creating context
Create Context with React.createContext()
↓
Wrap Components with Context.Provider
↓
Consume Context in Child with useContext()
↓
Child uses shared value from Context
↓
Update Context value triggers re-render of consumers
This flow shows how to create a context, provide a value, and consume it in child components, enabling shared state.
Execution Sample
React
const MyContext = React.createContext('default');

function Parent() {
  return <MyContext.Provider value="hello">
    <Child />
  </MyContext.Provider>;
}

function Child() {
  const value = React.useContext(MyContext);
  return <div>{value}</div>;
}
This code creates a context with a default, provides 'hello' as value, and Child reads and displays it.
Execution Table
StepActionContext ValueComponent RenderedOutput
1Create MyContext with default 'default''default'NoneNo output yet
2Parent renders and provides value 'hello''hello'ParentNo visible output
3Child renders inside Provider'hello'ChildRenders <div>hello</div>
4Child calls useContext(MyContext)'hello'ChildReads 'hello' from context
5Child displays context value'hello'ChildOutput: hello
6No further updates'hello'NoneExecution ends
💡 No more renders or updates, context value stable at 'hello'
Variable Tracker
VariableStartAfter Step 2After Step 3Final
MyContextReact Context with default 'default'SameSameSame
Context Value'default''hello''hello''hello'
Child Render OutputNoneNone<div>hello</div><div>hello</div>
Key Moments - 3 Insights
Why does Child get 'hello' instead of the default 'default'?
Because Parent wraps Child with MyContext.Provider and sets value to 'hello' (see execution_table step 2 and 3). The Provider value overrides the default.
What happens if we remove the Provider wrapping Parent?
Child would get the default value 'default' from MyContext (step 1), since no Provider sets a new value.
Does changing the Provider value update Child automatically?
Yes, if the Provider value changes, React re-renders Child with the new context value (not shown here but implied in step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the context value when Child renders?
A'hello'
B'default'
Cundefined
Dnull
💡 Hint
Check execution_table row 3 and 4 where Child renders and reads context
At which step does the Provider set the context value?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look at execution_table where Parent renders and provides value
If we remove the Provider, what would Child display?
A'hello'
BNothing
C'default'
DError
💡 Hint
Refer to variable_tracker Context Value at Start and key_moments about default value
Concept Snapshot
Creating context in React:
1. Use React.createContext(defaultValue) to make a context.
2. Wrap components with Context.Provider and set value prop.
3. Use useContext(Context) in children to read value.
4. Provider value overrides default.
5. Changing Provider value updates consumers automatically.
Full Transcript
Creating context in React involves making a context object with React.createContext, which holds a default value. Then, you wrap parts of your app with Context.Provider and give it a value to share. Inside children, you use the useContext hook to read that shared value. If no Provider is present, children get the default. When the Provider's value changes, React updates all consumers automatically. This lets components share data without passing props down many levels.

Practice

(1/5)
1. What is the main purpose of React's createContext() function?
easy
A. To manage local component state
B. To create a new React component
C. To fetch data from an API
D. To create a context object that allows sharing data without passing props manually

Solution

  1. Step 1: Understand what createContext() does

    This function creates a context object that can hold data to be shared across components without passing props manually.
  2. Step 2: Compare with other options

    Creating components, fetching data, or managing local state are unrelated to createContext().
  3. Final Answer:

    To create a context object that allows sharing data without passing props manually -> Option D
  4. Quick Check:

    Purpose of createContext() = share data without props [OK]
Hint: Remember: createContext() sets up shared data space [OK]
Common Mistakes:
  • Confusing context creation with component creation
  • Thinking it fetches data from APIs
  • Mixing it up with useState for local state
2. Which of the following is the correct way to create a context in React?
easy
A. const MyContext = useContext();
B. const MyContext = React.createContext();
C. const MyContext = createContext();
D. const MyContext = React.useContext();

Solution

  1. Step 1: Identify correct syntax for creating context

    The correct way is to call createContext() from the React object: React.createContext().
  2. Step 2: Check other options

    const MyContext = createContext(); misses the React prefix, which causes an error unless imported separately. Options A and D use useContext(), which is for consuming context, not creating it.
  3. Final Answer:

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

    Creating context = React.createContext() [OK]
Hint: Use React.createContext() to create context, not useContext() [OK]
Common Mistakes:
  • Using useContext() instead of createContext()
  • Omitting React prefix without import
  • Confusing creation and consumption functions
3. Given the code below, what will be logged to the console?
const MyContext = React.createContext('default');

function Display() {
  const value = React.useContext(MyContext);
  console.log(value);
  return null;
}

function App() {
  return (
    <MyContext.Provider value="hello">
      <Display />
    </MyContext.Provider>
  );
}
medium
A. "hello"
B. "default"
C. undefined
D. Error: useContext called outside provider

Solution

  1. Step 1: Understand context default and provider value

    The context default is "default", but the Display component is inside a provider with value "hello".
  2. Step 2: Determine value consumed by useContext

    Since Display is inside the provider, useContext(MyContext) returns "hello".
  3. Final Answer:

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

    Provider value overrides default = "hello" [OK]
Hint: Provider value overrides default context value [OK]
Common Mistakes:
  • Assuming default value is always used
  • Thinking useContext errors without provider
  • Confusing string quotes in output
4. Identify the error in the following React context usage:
const ThemeContext = React.createContext('light');

function Button() {
  const theme = React.useContext();
  return <button>Theme is {theme}</button>;
}
medium
A. Provider is missing around Button
B. Context should be created with useContext
C. Missing argument in useContext call
D. Button component must be class-based to use context

Solution

  1. Step 1: Check useContext usage

    The useContext hook requires the context object as an argument. Here, it is called without any argument.
  2. Step 2: Verify other options

    Context is correctly created with createContext. Provider is optional but not an error here. Functional components can use hooks, so no need for class-based.
  3. Final Answer:

    Missing argument in useContext call -> Option C
  4. Quick Check:

    useContext requires context argument [OK]
Hint: Always pass context object to useContext() [OK]
Common Mistakes:
  • Calling useContext() without argument
  • Confusing createContext and useContext
  • Thinking Provider is mandatory to avoid errors
5. You want to create a theme context that provides either "light" or "dark" mode to your app. Which approach correctly creates and uses this context with a provider and consumer component?
hard
A. const ThemeContext = React.createContext('light'); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; }
B. const ThemeContext = React.useContext('light'); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; }
C. const ThemeContext = React.createContext(); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(); return <div>Current theme: {theme}</div>; }
D. const ThemeContext = React.createContext('light'); function ThemeProvider({ children }) { const [theme, setTheme] = React.useState('dark'); return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; }

Solution

  1. Step 1: Check context creation and default value

    const ThemeContext = React.createContext('light'); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; } correctly creates context with default "light" using createContext('light').
  2. Step 2: Verify provider and consumer usage

    The provider passes "dark" as value, and consumer uses useContext(ThemeContext) correctly. const ThemeContext = React.createContext('light'); function ThemeProvider({ children }) { const [theme, setTheme] = React.useState('dark'); return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; } attempts to use state but misses the React. prefix on useState, causing ReferenceError. const ThemeContext = React.useContext('light'); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; } incorrectly calls React.useContext('light') instead of createContext(). const ThemeContext = React.createContext(); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(); return <div>Current theme: {theme}</div>; } calls useContext() without argument, causing error.
  3. Final Answer:

    Correctly creates and uses context with provider and consumer -> Option A
  4. Quick Check:

    Correct createContext and useContext with provider = const ThemeContext = React.createContext('light'); function ThemeProvider({ children }) { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> {children} </ThemeContext.Provider> ); } function DisplayTheme() { const theme = React.useContext(ThemeContext); return <div>Current theme: {theme}</div>; } [OK]
Hint: createContext with default, provider passes value, useContext consumes [OK]
Common Mistakes:
  • Using useContext instead of createContext to create context
  • Calling useContext without argument
  • Not passing provider value or missing provider
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