Skip to content

QuizNot attempted

useContext with no provider and no default

Display is rendered with no CountContext.Provider anywhere above it, and createContext() was called with no default value. What is rendered?
const CountContext = createContext();
function Display() {
const count = useContext(CountContext);
return <p>{count}</p>;
}
function App() {
return <Display />;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • <p></p> (renders undefined, i.e., nothing visible)
  • With no Provider above, useContext returns the default passed to createContext()
  • nothing was passed, so it is undefined, and React renders nothing for undefined: an empty <p>.
  • Not 'throws': a missing provider is not an error (custom hooks often throw on purpose).
  • Not null: null also renders nothing, but the value is undefined.
  • Not 0: that would need createContext(0).