createContext

Context<T> createContext<T>(

  1. T defaultValue
)

Creates a Context object with the specified defaultValue.

When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.

Example:

// Create a context with a default value
final ThemeContext = createContext('light');

// In a parent component, provide a value final provider = createElement( ThemeContext.providerType, createProps({'value': 'dark'}), MyComponent(), );

// In a child function component, consume the value final MyComponent = registerFunctionComponent((props) { final theme = useContext(ThemeContext); return div(children: [ pEl('Current theme: $theme'), ]); });

Implementation

Context<T> createContext<T>(T defaultValue) {
  final jsDefault = switch (defaultValue) {
    null => null,
    final Object obj => obj.jsify(),
  };
  final jsContext = JsContext.fromJs(_reactCreateContext(jsDefault));
  return Context._(jsContext, defaultValue);
}