useMemo
External Documentation
T
useMemo<
Returns a memoized version of the return value of createFunction.
If one of the dependencies has changed, createFunction is run during
rendering of the function component. This optimization helps to avoid
expensive calculations on every render.
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 MyComponent = registerFunctionComponent((props) {
final count = useState(0);
final fib = useMemo(
() => fibonacci(count.value),
[count.value],
);
return div(children: [
pEl('Fibonacci of ${count.value} is $fib'),
button(
text: '+',
onClick: () => count.setWithUpdater((prev) => prev + 1),
),
]);
});
Implementation
T useMemo<T>(T Function() createFunction, [List<Object?>? dependencies]) {
JSAny? jsCreateFunction() => _toJsAny(createFunction());
final jsDeps = (dependencies ?? <Object?>[]).map(_toJsAny).toList().toJS;
final result = React.useMemo(jsCreateFunction.toJS, jsDeps);
return switch (result.dartify()) {
final T v => v,
_ => throw StateError('useMemo returned unexpected type'),
};
}