Given the following React context and component, what will be rendered inside the <div>?
import React, { createContext, useContext } from 'react'; const ThemeContext = createContext('light'); function DisplayTheme() { const theme = useContext(ThemeContext); return <div>{`Current theme is: ${theme}`}</div>; } export default function App() { return ( <ThemeContext.Provider value="dark"> <DisplayTheme /> </ThemeContext.Provider> ); }
Remember that the value passed to the Provider overrides the default context value.
The ThemeContext.Provider sets the context value to "dark". The useContext hook inside DisplayTheme reads this value, so it renders "Current theme is: dark".
Consider this React component consuming a context with a count state. What will be the value of count after clicking the button once?
import React, { createContext, useContext, useState } from 'react'; const CountContext = createContext(); function Counter() { const { count, setCount } = useContext(CountContext); return <button onClick={() => setCount(count + 1)}>Increment</button>; } export default function App() { const [count, setCount] = useState(0); return ( <CountContext.Provider value={{ count, setCount }}> <Counter /> <p>{`Count is: ${count}`}</p> </CountContext.Provider> ); }
Clicking the button calls setCount(count + 1) which updates the state.
The initial count is 0. Clicking the button calls setCount(1), so the count updates to 1 and the paragraph shows "Count is: 1".
Which code snippet correctly consumes a React context with a default value fallback when no Provider is used?
import React, { createContext, useContext } from 'react'; const UserContext = createContext('Guest'); function Welcome() { // Fill in the blank const user = /* ??? */; return <p>Welcome, {user}!</p>; }
Use the useContext hook with the context object as argument.
The correct way to consume context is useContext(UserContext). Options B, C, and D are invalid syntax or usage.
Given this code, why does DisplayUser throw an error?
import React, { createContext, useContext } from 'react'; const UserContext = createContext(); function DisplayUser() { const user = useContext(UserContext); return <p>User: {user.name}</p>; } export default function App() { return <DisplayUser />; }
Check what useContext returns when no Provider is present.
Since UserContext has no default value and no Provider wraps DisplayUser, useContext returns undefined. Accessing user.name causes a runtime error.
Choose the statement that correctly describes how React context consumption works with useContext and Providers.
Think about how context values propagate in React component trees.
useContext reads the value from the nearest Provider above it in the React tree. If no Provider exists, it returns the default value given when creating the context.