useStateLazy
External Documentation
StateHook<
Adds local state to a function component by returning a StateHook with
StateHook.value initialized to the return value of init.
Use this when the initial state is expensive to compute.
Example:
final MyComponent = registerFunctionComponent((props) {
final count = useStateLazy(() {
// Expensive computation here
return someExpensiveComputation(props);
});
return div(children: [
pEl('Count: ${count.value}'),
]);
});
Implementation
StateHook<T> useStateLazy<T>(T Function() init) {
JSAny? jsInit() {
final val = init();
return switch (val) {
null => null,
final Object obj => obj.jsify(),
};
}
final result = React.useState(jsInit.toJS);
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));
}