Bird
Raised Fist0
Reactframework~20 mins

Creating context in React - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Context Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this React context example?

Consider this React code using context:

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

const MyContext = createContext('default');

function Display() {
  const value = useContext(MyContext);
  return <div>Value: {value}</div>;
}

export default function App() {
  return (
    <MyContext.Provider value="hello">
      <Display />
    </MyContext.Provider>
  );
}

What will be rendered inside the <div>?

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

const MyContext = createContext('default');

function Display() {
  const value = useContext(MyContext);
  return <div>Value: {value}</div>;
}

export default function App() {
  return (
    <MyContext.Provider value="hello">
      <Display />
    </MyContext.Provider>
  );
}
AValue: default
BValue: null
CValue: hello
DValue: undefined
Attempts:
2 left
💡 Hint

Check what value is passed to the Provider and what useContext reads.

❓ state_output
intermediate
2:00remaining
What is the value of count after clicking the button twice?

Given this React component using context and state:

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

const CountContext = createContext();

function Counter() {
  const { count, setCount } = useContext(CountContext);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <CountContext.Provider value={{ count, setCount }}>
      <Counter />
    </CountContext.Provider>
  );
}

After clicking the button two times, what is the value of count shown?

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

const CountContext = createContext();

function Counter() {
  const { count, setCount } = useContext(CountContext);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <CountContext.Provider value={{ count, setCount }}>
      <Counter />
    </CountContext.Provider>
  );
}
ACount: 2
BCount: 1
CCount: 0
DCount: NaN
Attempts:
2 left
💡 Hint

Each click increments count by 1 starting from 0.

📝 Syntax
advanced
2:00remaining
Which option correctly creates a React context with a default value?

Choose the correct code to create a React context with default value "guest".

Aconst UserContext = createContext({ default: 'guest' });
Bconst UserContext = createContext('guest');
Cconst UserContext = createContext(); UserContext.defaultValue = 'guest';
Dconst UserContext = createContext; UserContext('guest');
Attempts:
2 left
💡 Hint

Look for the correct way to call createContext with a default value.

🔧 Debug
advanced
2:00remaining
Why does this React context example cause an error?

Examine this code snippet:

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

const ThemeContext = createContext();

function DisplayTheme() {
  const theme = useContext(ThemeContext);
  return <div>Theme: {theme.color}</div>;
}

export default function App() {
  return <DisplayTheme />;
}

What error will occur when this runs?

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

const ThemeContext = createContext();

function DisplayTheme() {
  const theme = useContext(ThemeContext);
  return <div>Theme: {theme.color}</div>;
}

export default function App() {
  return <DisplayTheme />;
}
ANo error, renders 'Theme: undefined'
BSyntaxError: Unexpected token
CReferenceError: ThemeContext is not defined
DTypeError: Cannot read property 'color' of undefined
Attempts:
2 left
💡 Hint

Check what value useContext returns when no Provider is used.

🧠 Conceptual
expert
2:00remaining
Which option best explains React context behavior when Provider value changes?

In React, when a context Provider's value prop changes, what happens to components consuming that context?

AConsuming components re-render only if the new context value is a different reference than before.
BOnly consuming components that use <code>useMemo</code> re-render with the new value.
CAll consuming components re-render immediately with the new context value.
DConsuming components never re-render automatically; you must force update manually.
Attempts:
2 left
💡 Hint

Think about how React compares context values to decide re-rendering.

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