Skip to main content
Retrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation. createContext is a type-safe alternative.

Signature

Parameters

key
any
required
The key used by a parent component when calling setContext. This should match exactly the key used in the parent.

Returns

context
T
Returns the context object that was set by a parent component, or undefined if no parent has set a context with this key.

Example

Parent Component

Child Component

Nested Child Component

Type-Safe Context

For better type safety, use createContext:

Notes

  • Must be called during component initialisation (not in callbacks or effects)
  • Returns undefined if no parent component has set a context with the given key
  • Use hasContext to check if a context exists before calling getContext
  • Context lookup traverses up the component tree until it finds a matching key