Lifecycle của surface
useAppContext().lifecycle sở hữu resource cho một surface mount. Cleanup chạy khi unmount hoặc exact runtime identity đổi.
| API | Cách dùng |
|---|---|
signal | AbortSignal bị abort khi unmount. |
onDispose(dispose) | Đăng ký cleanup của app và trả về hàm unregister. |
listen(target, type, listener, options?) | Thêm event listener thuộc mount này và trả về disposer. |
import { useEffect, useState } from 'react';
import { useAppContext } from '@sota/platform';
export function OnlineState() {
const { lifecycle } = useAppContext();
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
const stopOnline = lifecycle.listen(window, 'online', update);
const stopOffline = lifecycle.listen(window, 'offline', update);
return () => { stopOnline(); stopOffline(); };
}, [lifecycle]);
return <p>{online ? 'Online' : 'Offline'}</p>;
}import { useEffect } from 'react';
import { useAppContext } from '@sota/platform';
export function MountTimer() {
const { lifecycle } = useAppContext();
useEffect(() => {
const timer = window.setInterval(() => console.log('tick'), 30_000);
const unregister = lifecycle.onDispose(() => window.clearInterval(timer));
return () => {
window.clearInterval(timer);
unregister();
};
}, [lifecycle]);
return null;
}Dùng primitives này thay cho listener hoặc timer toàn process. React có thể dispose sớm; Core vẫn đảm bảo cleanup cưỡng bức khi surface biến mất.