Question presented to candidate: "What is the Context API, and how do you decide whether a value belongs in it?"
What a strong answer should cover:
createContextmakes a context; a provider supplies a value; any descendant reads it withuseContext.- It solves prop drilling — delivering a value without threading it through intermediate components.
- It is a transport mechanism, not a state manager. It does not store or update anything; the state still lives in a component or a store, and Context merely carries it.
- The cost: every consumer re-renders when the provider value changes, and
memodoes not stop that. - So it suits values that are read widely and change rarely: theme, locale, current user, feature flags, a stable
dispatch. - It suits badly: anything changing frequently, like form input or cursor position.
- The default value is only used when a consumer has no provider above it — useful for tests and for catching missing providers.
- Convention: wrap the
useContextcall in a custom hook that throws when the provider is missing. - Multiple small contexts beat one large object, because the granularity of re-rendering follows the granularity of the contexts.
Clarifying questions expected:
- "How often does this value change, and how many components read it?"
- "Have we tried composition first?" — often it removes the need entirely.
Code / implementation expected: Yes — a provider, a custom consumer hook with a missing-provider guard, and a memoised value.