useEffect
External Documentation
void
useEffect(
Runs sideEffect after every completed render of a function component.
If dependencies are given, sideEffect will only run if one of the
dependencies have changed. sideEffect may return a cleanup function
that is run before the component unmounts or re-renders.
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(1);
final evenOdd = useState('even');
useEffect(() {
evenOdd.set(count.value % 2 == 0 ? 'even' : 'odd');
return () {
print('cleanup: count is changing...');
};
}, [count.value]);
return div(children: [
pEl('${count.value} is ${evenOdd.value}'),
button(text: '+', onClick: () => count.set(count.value + 1)),
]);
});
Implementation
void useEffect(Object? Function() sideEffect, [List<Object?>? dependencies]) {
JSAny? wrappedSideEffect() {
final result = sideEffect();
return (result is void Function()) ? result.toJS : _jsUndefined;
}
final jsDeps = dependencies?.map(_toJsAny).toList().toJS;
React.useEffect(wrappedSideEffect.toJS, jsDeps);
}