key. Must be called during component initialisation.
createContext is a type-safe alternative.
Signature
Parameters
The key used by a parent component when calling
setContext. This should match exactly the key used in the parent.Returns
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, usecreateContext:
Notes
- Must be called during component initialisation (not in callbacks or effects)
- Returns
undefinedif no parent component has set a context with the given key - Use
hasContextto check if a context exists before callinggetContext - Context lookup traverses up the component tree until it finds a matching key