useContext

External Documentation

T useContext<T>(

  1. Context<T> context
)

Accepts a Context object and returns the current context value for that context.

The current context value is determined by the value prop of the nearest <Context.Provider> above the calling component in the tree.

When the nearest <Context.Provider> above the component updates, this Hook will trigger a rerender with the latest context value passed to that provider.

Note: there are two rules for using Hooks:

  • Only call Hooks at the top level.
  • Only call Hooks from inside a function component.

Example:

final ThemeContext = createContext('light');

final ThemedButton = registerFunctionComponent((props) { final theme = useContext(ThemeContext); return button( text: 'Click me', style: {'background': theme == 'dark' ? '#333' : '#fff'}, ); });

Implementation

T useContext<T>(Context<T> context) {
  final jsValue = _reactUseContext(context.jsContext);
  return switch (jsValue) {
    null => context.defaultValue,
    final v => switch (v.dartify()) {
      final T val => val,
      _ => context.defaultValue,
    },
  };
}