---
title: "Lifecycle của surface"
description: "useAppContext().lifecycle sở hữu resource cho một surface mount. Cleanup chạy khi unmount hoặc exact runtime identity đổi."
url: "https://sotaagents.ai/vi/manual/developer-guide/surface-lifecycle"
generated_by: "sotaagents-ldp"
docs_index: "https://sotaagents.ai/manual/llms.txt"
locale: "vi"
---

# 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. |

TSX

```
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>;
}
```

TypeScript

```
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.
