useStateJS

External Documentation

StateHookJS useStateJS(

  1. JSAny? initialValue
)

Adds local state for JS interop types to a function component.

Use this instead of useState when state must remain as a JS type (JSString, JSObject, etc.) without Dart conversion.

Example:

final tokenState = useStateJS(null);
final token = tokenState.value; // JSAny?
tokenState.set('abc'.toJS);

Implementation

StateHookJS useStateJS(JSAny? initialValue) {
  final result = React.useState(initialValue);
  final jsValue = result[0];
  final setter = switch (result[1]) {
    final JSFunction fn => fn,
    _ => throw StateError('useState setter is not a function'),
  };
  return StateHookJS._(jsValue, (v) => setter.callAsFunction(null, v));
}