context object with the current component and the specified key and returns that object. The context is then available to children of the component (including slotted content) with getContext.
Like lifecycle functions, this must be called during component initialisation.
createContext is a type-safe alternative.
Signature
Parameters
The key to associate with the context. This can be any value (string, symbol, object, etc.).
The context object to associate with the key. This can be any value and will be returned unchanged.
Returns
Returns the same context object that was passed in.
Example
Parent Component
Child Component
Type-Safe Context
For better type safety, consider usingcreateContext instead:
Notes
- Must be called during component initialisation (not in callbacks or effects)
- Context is available to all descendant components, including slotted content
- Context is scoped to the component tree, not globally
- Using symbols as keys helps avoid naming conflicts between different libraries