useState

External Documentation

StateHook<T> useState<T>(

  1. T initialValue
)

Adds local state to a function component by returning a StateHook with StateHook.value initialized to initialValue.

Note: If the initialValue is expensive to compute, useStateLazy should be used instead.

Example:

final MyComponent = registerFunctionComponent((props) {
  final count = useState(0);

return div(children: [ pEl('Count: ${count.value}'), button( text: 'Increment', onClick: () => count.setWithUpdater((prev) => prev + 1), ), ]); });

Implementation

StateHook<T> useState<T>(T initialValue) {
  final jsInitial = switch (initialValue) {
    null => null,
    final Object obj => obj.jsify(),
  };
  final result = React.useState(jsInitial);
  final jsValue = result[0];
  final value = (jsValue == null) ? null : jsValue.dartify();
  final setter = switch (result[1]) {
    final JSFunction fn => fn,
    _ => throw StateError('useState setter is not a function'),
  };
  final typedValue = switch (value) {
    final T v => v,
    null => null as T,
    _ => throw StateError('useState value type mismatch'),
  };
  return StateHook._(typedValue, (v) => setter.callAsFunction(null, v));
}