createContextInit<TValue> function

Context<TValue> createContextInit<TValue>(
  1. TValue defaultValue, [
  2. int calculateChangedBits(
    1. TValue,
    2. TValue
    )?
])

Creates a Context object.

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.

defaultValue must be provided in order to create a context with a non-nullable generic type, and is only used when a component does not have a matching Context.Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.

To create a context without a default value, use createContext (caveat: the generic type has to be nullable).

Example:

final MyContext = createContext<String>('default value');

example() {
  return Fragment()(
    (MyContext.Provider()..value = 'new context value')(
      // Consume using either a function component, class component, or Context.Consumer utility.
      // Each of the following children renders a span with 'new context value'.
      ExampleFunctionConsumer()(),
      ExampleClassConsumer()(),
      MyContext.Consumer()(
        (value) => Dom.span()(value),
      ),
    ),

    // When not nested in a matching Provider, the default value is used.
    ExampleFunctionConsumer()(), // Renders a span with 'default value'.
  );
}

mixin ExampleFunctionConsumerProps on UiProps {}
UiFactory<ExampleFunctionConsumerProps> ExampleFunctionConsumer = uiFunction((props) {
  final contextValue = useContext(MyContext);
  return Dom.span()(contextValue);
}, _$ExampleFunctionConsumerConfig);

UiFactory<ExampleClassConsumerProps> ExampleClassConsumer = castUiFactory(_$ExampleClassConsumer);
mixin ExampleClassConsumerProps on UiProps {}
class ExampleClassConsumerComponent extends UiComponent2<ExampleClassConsumerProps> {
  @override
  get contextType => MyContext.reactDartContext;

  render() {
    return Dom.span()(this.context);
  }
}

Learn more: react.dev/reference/react/createContext

Implementation

Context<TValue> createContextInit<TValue>(TValue defaultValue, [int Function(TValue, TValue)? calculateChangedBits]) {
  final reactDartContext = react.createContext<TValue>(defaultValue, calculateChangedBits != null ? (dynamic arg1, dynamic arg2) => calculateChangedBits(arg1 as TValue, arg2 as TValue) : null);
  return Context<TValue>.fromReactDartContext(reactDartContext);
}