Consider this React code using Context. What will be rendered inside the <Display> component?
import React, { createContext, useContext } from 'react'; const MyContext = createContext('default'); function Display() { const value = useContext(MyContext); return <p>{value}</p>; } function App() { return ( <MyContext.Provider value="Hello, world!"> <Display /> </MyContext.Provider> ); } export default App;
Think about what value the Context Provider passes down.
The <Display> component uses useContext to get the value from MyContext. Since App wraps Display with MyContext.Provider and sets the value to "Hello, world!", that is what Display renders.
Given this React context and component, what is the final value of count displayed?
import React, { createContext, useContext, useState } from 'react'; const CountContext = createContext(); function Counter() { const { count, setCount } = useContext(CountContext); setCount(count + 1); return <p>{count}</p>; } function App() { const [count, setCount] = useState(0); return ( <CountContext.Provider value={{ count, setCount }}> <Counter /> </CountContext.Provider> ); } export default App;
Consider what happens when setCount is called inside the component body.
Calling setCount directly inside the component body causes the component to re-render infinitely, because each render triggers setCount again. This leads to an infinite loop error.
Which code snippet correctly creates a React Context with a default value and consumes it inside a component?
Remember how useContext is called with the Context object.
Option A correctly creates a Context with default value 'light' and uses useContext(ThemeContext) to consume it. Other options misuse useContext or call it incorrectly.
Look at this React code. The Display component does not update when the Provider's value changes. Why?
import React, { createContext, useContext, useState } from 'react'; const NumberContext = createContext(0); function Display() { const value = useContext(NumberContext); return <p>{value}</p>; } function App() { const [num, setNum] = useState(0); function update() { setNum(num + 1); } return ( <NumberContext.Provider value={num}> <Display /> <button onClick={update}>Increase</button> </NumberContext.Provider> ); } export default App;
How should React state be updated to trigger re-render?
In React, state variables must be updated using their setter functions (like setNum). Directly changing num does not trigger a re-render, so the context value stays the same from React's perspective.
Which option describes the best practice to avoid unnecessary re-renders when using React Context?
Think about how React decides to re-render components consuming context.
Option B is best practice because limiting Provider scope and memoizing context values reduce unnecessary re-renders. Passing new objects every time (option B) causes all consumers to re-render. Option B is impractical for large apps. Option B is incorrect usage of Context.