---
title: "useSticky 用法與示例"
description: "跟蹤元素是否粘滞。"
canonical: https://reactuse.com/zh-Hant/element/usesticky/
---

# useSticky

跟蹤元素是否粘滞

`useSticky` 偵測一個 `position: sticky` 元素是否當前處於黏附（stuck）狀態。它使用 Intersection Observer 以零閾值觀察元素，確定元素是否已黏附到容器邊界。回傳一個布林值和一個需要綁定到目標元素的 ref。

### 使用場景

- 當黏附標題處於黏附狀態時新增陰影或邊框樣式
- 在黏附導覽列啟動時更改其背景或外觀
- 追蹤黏附元素的狀態以進行分析或條件渲染

### 注意事項

- **SSR 安全**：在伺服器端渲染時回傳 `false`。伺服器上不會建立 `IntersectionObserver`。
- **CSS 要求**：目標元素必須設定 `position: sticky` CSS 屬性才能使此 hook 正常工作。
- **相關 hooks**：另請參閱 `useIntersectionObserver` 用於一般的交集觀察，以及 `useScroll` 追蹤捲動位置。

## Usage

```tsx live
function Demo() {
  const element = useRef<HTMLDivElement>(null);
  const [isSticky] = useSticky(element, {
    // header fixed height
    nav: 64,
  });

  const stickyStyle: CSSProperties = isSticky
    ? {
        position: "fixed",
        top: 64,
        zIndex: 50,
        height: 20,
      }
    : {
        height: 20,
      };

  const guardStyle: CSSProperties = {
    width: 1,
    height: 1,
  };

  return (
    <div style={{height: 300,overflow: 'scroll'}}>
      <div ref={element} style={guardStyle} />
      <button style={stickyStyle}>
        {isSticky ? "stickying" : "not sticky"}
      </button>
      <div style={{ height: "100vh" }} />
    </div>
  );
};
```

%%API%%