call(back)

Which Statement About React Context Is Correct?

Which statement about context is correct in React 16.3 and later? Explain why the others are wrong.

  • A. Context can only be accessed in class components, using this.context.
  • B. A React context is created with React.createContext().
  • C. The only way to access context in function components is the Consumer component.
  • D. Context values must always be primitive data types.

Hints

Hint 1

Think about how a function component reads context today, and what kinds of values a provider can hold.

Solution

Show the approach

Answer: B

A is wrong: useContext and Consumer work outside classes. C is wrong: useContext exists. D is wrong: any value works, objects and functions included.

Worth saying out loud

  • Context is for values many components need (theme, locale, the signed-in user), not a replacement for props or a state manager.
  • A provider value that's a new object on every render re-renders every consumer; memoize it.

Asked at