@ariefsn/svelte-use

中文文档
1.2.1发布于 2026/09/28MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 1904

Collection of reactive utility composables for Svelte 5 inspired by VueUse.

原始使用文档
文档目录63 节
  1. Features
  2. Installation
  3. Utilities
  4. Animation
  5. Async
  6. Time
  7. State
  8. Reactivity
  9. Browser – Keyboard & Scroll
  10. Browser – Pointer & Drag
  11. Browser – Observers
  12. Browser – Sensors
  13. Browser – Storage
  14. Browser – Interaction
  15. Performance
  16. Virtualization
  17. Web APIs
  18. Browser – Appearance
  19. Browser – Document
  20. Browser – Media
  21. Head & SEO
  22. Browser – Navigation
  23. Composable Reference
  24. useToggle
  25. useCounter
  26. usePrevious
  27. useDebounce
  28. useLocalStorage
  29. useIndexedDB
  30. useSorted
  31. useCycleList
  32. useCountdown
  33. useTimeAgo
  34. useMagicKeys
  35. useKeyModifier
  36. useScroll
  37. useMouse
  38. useMousePressed
  39. useDraggable
  40. useElementSize
  41. useIntersectionObserver
  42. useResizeObserver
  43. useMutationObserver
  44. useIdle
  45. useNetwork
  46. useGeolocation
  47. useFetch
  48. useWebSocket
  49. useAnimate
  50. useParallax
  51. useTransition
  52. useInterval
  53. useNow
  54. useTimestamp
  55. useBreakpoints
  56. useClipboard
  57. useBattery
  58. useVirtualList
  59. Developing
  60. Building & Publishing
  61. Links
  62. Star History
  63. License
svelte-use logo

@ariefsn/svelte-use

A collection of 100+ Svelte 5 runes-first utility composables.
No stores. No external dependencies. SSR-safe. Fully typed.

GitHub npm version npm downloads Svelte 5 TypeScript


Features

⚡ Svelte 5 RunesBuilt for $state, $derived, $effect — no stores
🌲 Tree-shakableImport only what you use
🔒 Fully typedFirst-class TypeScript, no any
🌐 SSR safeAll browser APIs are guarded
📦 Zero depsNo runtime dependencies
🧹 Auto cleanupListeners removed on component destroy

Installation

npm install @ariefsn/svelte-use
# or
pnpm add @ariefsn/svelte-use
# or
bun add @ariefsn/svelte-use

Requires Svelte 5 as a peer dependency.


Utilities

Animation

ComposableDescription
useAnimateReactive Web Animations API wrapper
useRafFnRun a callback on every animation frame
useParallaxParallax effect based on pointer or device tilt
useTransitionAnimated numeric transitions with easing

Async

ComposableDescription
useFetchReactive fetch with loading/error state
useWebSocketReactive WebSocket with auto-reconnect
useAsyncStateReactive async/promise state with loading/error
useEventSourceServer-sent events; the browser handles reconnection
useBroadcastChannelCross-tab messaging by structured clone
useAsyncQueueRun async tasks with bounded concurrency

Time

ComposableDescription
useIntervalReactive interval counter
useIntervalFnRun a callback on an interval
useNowReactive current Date
useTimeoutReactive timeout flag
useTimeoutFnRun a callback after a delay
useTimeoutPollPoll a callback with timeout-based intervals
useTimestampReactive current timestamp (ms)

State

ComposableDescription
useToggleReactive boolean toggle
useCounterReactive counter with inc/dec/reset
usePreviousTrack previous value of any reactive getter
useSortedReactive sorted copy of an array
useCycleListCycle through a list reactively
useCountdownCountdown timer with start/stop/reset
useTimeAgoHuman-readable relative time string
useAutoResetStateState that auto-resets to default after delay
useDefaultStateState with fallback for null/undefined
useLastChangedTimestamp of last reactive value change
useTrackHistoryUndo/redo history for reactive values
useHistoryStateState with built-in undo/redo history
useStateMachineTyped finite state machine, inferred from the config
useOffsetPaginationPagination state that self-corrects when totals shrink
useConfirmDialogConfirmation flow as a single await

Reactivity

ComposableDescription
useDebounceDebounce any reactive getter
useWatchWatch reactive values with current/previous args
useWheneverWatch that fires only when value becomes truthy
useUntilAwait a reactive value reaching a condition
useClonedDeep copy of a reactive value, for edit buffers

Browser – Keyboard & Scroll

ComposableDescription
useMagicKeysReactive keyboard state via Proxy — single keys or combos
useKeyModifierTrack Ctrl/Shift/Alt/Meta state
useScrollScroll position, direction, edge arrival
useScrollLockLock/unlock body scroll
useInfiniteScrollLoad more content as a container nears its edge

Browser – Pointer & Drag

ComposableDescription
useMouseViewport-relative pointer position
useMousePressedDetect mouse button press state
useMouseInElementPointer position relative to an element
useDraggableFull-featured draggable with axis, bounds, handles

Browser – Observers

ComposableDescription
useElementSizeReactive element dimensions via ResizeObserver
useElementBoundingReactive full bounding box, position included
useIntersectionObserverVisibility detection via IntersectionObserver
useResizeObserverRaw ResizeObserver with callback
useMutationObserverDOM mutation observation

Browser – Sensors

ComposableDescription
useMediaQueryReactively track whether a CSS media query matches
useWindowSizeReactive viewport dimensions
useIdleDetect user idle state
useNetworkNetwork Information API (downlink, RTT, effectiveType)
useGeolocationReactive geolocation via watchPosition
useBreakpointsReactive responsive breakpoints
useBrowserLocationReactive browser location (URL, hash, search)
useNavigatorLanguageReactive navigator language
useOnlineReactive online/offline status
usePageLeaveDetect when user leaves the page
useDocumentVisibilityReactive document visibility state
useWindowFocusTrack whether browser window is focused
useDeviceMotionDevice acceleration and rotation data
useDeviceOrientationDevice physical orientation (alpha/beta/gamma)
useDevicePixelRatioReactive device pixel ratio for Retina detection
useScreenOrientationScreen orientation and angle, with locking
useGamepadGamepad state, polled only while one is connected
useScrollbarWidthMeasure scrollbar width of an element

Browser – Storage

ComposableDescription
useStorageReactive Web Storage (local or session)
useLocalStorageReactive localStorage with SSR safety
useIndexedDBReactive IndexedDB with CRUD & querying
useBase64Reactive Base64 encode/decode
useObjectUrlReactive object URL from Blob/File
useSessionStorageReactive sessionStorage with SSR safety

Browser – Interaction

ComposableDescription
useClickOutsideDetect clicks outside an element
useDropZoneDrag-and-drop zone with file/data support
useElementHoverDetect hover state of an element
useFocusReactive focus state of an element
useActiveElementTrack currently focused element globally
useLongPressLong press gesture detection
useStartTypingDetect typing on non-editable elements
useTextareaAutosizeGrow a textarea to fit its content
useSwipeTouch swipe gesture detection

Performance

ComposableDescription
useFpsReactive frames-per-second counter
useThrottleFnThrottle any function
useDebounceFnDebounce any function
useWebWorkerFnRun a self-contained function off the main thread
useMemoizeCache a function's results by its arguments, with LRU

Virtualization

ComposableDescription
useVirtualListEfficient virtual list rendering

Web APIs

ComposableDescription
useClipboardReactive clipboard read/write
useBatteryReactive Battery Status API
useSpeechRecognitionReactive Web Speech Recognition API
useEyeDropperEyeDropper API for color picking
useFileDialogProgrammatic file input dialog
useShareNative Web Share API
useVibrateVibration API
useWebNotificationDesktop notifications API
usePermissionBrowser Permissions API
useWakeLockScreen Wake Lock API
useFullscreenDisplay any element fullscreen, Escape-aware
useImagePreload an image and track its load state
useSpeechSynthesisText-to-speech, with async voice loading handled
useFileSystemAccessRead and write real files (Chromium only)
useSupportedSSR-safe one-shot feature detection
useEventListenerGeneric event listener with cleanup
useTextDirectionTrack/set text directionality
useTextSelectionTrack text selection

Browser – Appearance

ComposableDescription
useColorModeColour mode with auto resolution, persistence and sync
usePreferredDarkWhether the OS requests a dark colour scheme
usePreferredColorSchemeOS colour scheme as dark / light / no-preference
usePreferredReducedMotionWhether the OS requests reduced motion
usePreferredContrastOS contrast preference, including forced colours
useCssVarRead and write a CSS custom property

Browser – Document

ComposableDescription
useTitleRead and write document.title, restored on destroy
useFaviconRead and write the favicon, adopting an existing link
useStyleTagInject a <style> element, deduplicated by id
useScriptTagLoad an external script, deduplicated across call sites

Browser – Media

ComposableDescription
useUserMediaCamera and microphone capture, device switching, preview mirroring
useDisplayMediaScreen capture that notices the browser's "Stop sharing"
useDevicesListMedia devices grouped by kind, refreshed on devicechange

Head & SEO

ComposableDescription
useSeoLayered SEO metadata as a builder, rendered into <svelte:head>
SeoComponent that renders useSeo output — the only component here

Browser – Navigation

ComposableDescription
useNavigationGuardNavigation guard with confirm/cancel — requires SvelteKit
useUrlSearchParamsReactive URL query parameters, with history and hash modes

Note: useNavigationGuard is the only composable here that is not plain-Svelte. It imports beforeNavigate and goto from $app/navigation, so it works in SvelteKit apps only; @sveltejs/kit is not a declared peer dependency. Every other composable in this library runs in any Svelte 5 app.


Composable Reference

useToggle

Reactive boolean toggle.

import { useToggle } from '@ariefsn/svelte-use';

const { value, toggle, set } = useToggle();
// value → false
toggle(); // value → true
set(false); // value → false
ReturnTypeDescription
valueboolean (reactive)Current boolean state
toggle() => voidFlips the value
set(v: boolean) => voidSets the value explicitly

useCounter

Reactive counter with increment, decrement, and reset.

import { useCounter } from '@ariefsn/svelte-use';

const { value, inc, dec, reset } = useCounter(0);
inc(); // value → 1
inc(5); // value → 6
dec(3); // value → 3
reset(); // value → 0
ReturnTypeDescription
valuenumber (reactive)Current counter value
inc(delta?: number) => voidIncrement by delta (default 1)
dec(delta?: number) => voidDecrement by delta (default 1)
reset() => voidReset to initial value

usePrevious

Tracks the previous value of any reactive getter. Returns undefined until the tracked value changes for the first time.

import { usePrevious } from '@ariefsn/svelte-use';

let count = $state(0);
const prev = usePrevious(() => count);
// prev() → undefined
count = 1;
// prev() → 0
count = 2;
// prev() → 1
ParameterTypeDescription
getter() => TReactive getter function to observe

Returns a () => T | undefined getter.


useDebounce

Delays a reactive value until the source stops changing for the specified duration.

import { useDebounce } from '@ariefsn/svelte-use';

let query = $state('');
const debounced = useDebounce(() => query, 500);
// debounced() updates only after 500 ms of inactivity
ParameterTypeDefaultDescription
getter() => T—Reactive getter to debounce
delaynumber300Delay in milliseconds

Returns a () => T getter.


useLocalStorage

Reactive localStorage with SSR safety. Values are serialised with JSON.stringify / JSON.parse. Falls back to initial in non-browser environments or on parse errors.

import { useLocalStorage } from '@ariefsn/svelte-use';

const theme = useLocalStorage<'light' | 'dark'>('theme', 'light');
theme.set('dark'); // persists to localStorage
theme.value; // 'dark'
ParameterTypeDescription
keystringlocalStorage key
initialTFallback when key is absent or in SSR
ReturnTypeDescription
valueT (reactive)Current stored value
set(v: T) => voidUpdate and persist the value

useIndexedDB

Reactive IndexedDB utility with full CRUD, querying, and filtering. SSR-safe — all operations are no-ops on the server. Values survive page refreshes and browser restarts.

import { useIndexedDB } from '@ariefsn/svelte-use';

interface Note {
    id?: number;
    text: string;
    done: boolean;
}

const db = useIndexedDB<Note>('my-app', 'notes');

// CRUD
await db.add({ text: 'Buy milk', done: false }); // returns generated key
await db.get(1); // Note | undefined
await db.getAll(); // Note[]
await db.update({ id: 1, text: 'Buy milk', done: true });
await db.remove(1);
await db.clear(); // delete all records

// Reactive state (updated automatically after every mutation)
db.items; // Note[]   — all records
db.loading; // boolean
db.error; // Error | null

// Filtering
const pending = await db.query((n) => !n.done); // Note[]

Options

ParameterTypeDefaultDescription
dbNamestring—IndexedDB database name
storeNamestring—Object store name
options.versionnumber1Schema version (increment to migrate)
options.keyPathstring'id'Primary key field name
options.autoIncrementbooleantrueAuto-generate numeric keys

Returns

Property / MethodTypeDescription
itemsT[] (reactive)All stored records; refreshed after every mutation
loadingboolean (reactive)true while an async operation is in flight
errorError | null (reactive)Last error, or null
add(record)Promise<IDBValidKey | undefined>Insert record; returns generated key
get(key)Promise<T | undefined>Fetch single record by primary key
getAll()Promise<T[]>Fetch all records and sync items
update(record)Promise<void>Replace record (must include key field)
remove(key)Promise<void>Delete record by primary key
query(filter)Promise<T[]>Return records matching a predicate (doesn't modify items)
clear()Promise<void>Delete all records

useSorted

Returns a reactive sorted copy of an array. Never mutates the source.

import { useSorted } from '@ariefsn/svelte-use';

let items = $state([3, 1, 4, 1, 5]);
const sorted = useSorted(() => items);
// sorted() → [1, 1, 3, 4, 5]

const desc = useSorted(
    () => items,
    (a, b) => b - a
);

useCycleList

Cycle through a list reactively. Wraps around at both ends.

import { useCycleList } from '@ariefsn/svelte-use';

const cycle = useCycleList(['light', 'dark', 'system']);
cycle.state(); // → 'light'
cycle.next(); // → 'dark'
cycle.prev(); // → 'light'
cycle.setIndex(2);

useCountdown

Countdown timer with start/stop/reset.

import { useCountdown } from '@ariefsn/svelte-use';

const timer = useCountdown(60); // 60s at 1s intervals
timer.start();
timer.count(); // → 60, 59, …, 0
timer.isActive(); // → true
timer.stop();
timer.reset();

useTimeAgo

Reactive human-readable relative time string.

import { useTimeAgo } from '@ariefsn/svelte-use';

const ago = useTimeAgo(() => new Date('2024-01-01'));
ago(); // → "1 year ago"

useMagicKeys

Track any key or combination via a Proxy.

import { useMagicKeys } from '@ariefsn/svelte-use';

const keys = useMagicKeys();
keys['ctrl+s'](); // → true while Ctrl+S is held
keys['shift'](); // → true while Shift is held

useKeyModifier

Track a specific modifier key state.

import { useKeyModifier } from '@ariefsn/svelte-use';

const ctrl = useKeyModifier('ctrl'); // 'ctrl' | 'shift' | 'alt' | 'meta'
ctrl(); // → true while Ctrl is held

useScroll

Scroll position, direction flags, edge detection for any scrollable element or window.

import { useScroll } from '@ariefsn/svelte-use';

const scroll = useScroll(); // window
const elScroll = useScroll(() => myEl, { offset: { bottom: 20 } });

scroll.y(); // → number
scroll.isScrolling(); // → boolean
scroll.arrivedState.bottom(); // → boolean
scroll.directions.down(); // → boolean
scroll.scrollTo({ top: 0 });

useMouse

Tracks viewport-relative pointer position.

import { useMouse } from '@ariefsn/svelte-use';

const mouse = useMouse();
mouse.x(); // → number
mouse.y(); // → number
mouse.sourceType(); // → 'mouse' | 'touch' | null

useMousePressed

Detects whether any mouse button is held.

import { useMousePressed } from '@ariefsn/svelte-use';

const pressed = useMousePressed();
pressed(); // → boolean

useDraggable

Full-featured draggable with axis constraints, bounds, handles, and callbacks.

import { useDraggable } from '@ariefsn/svelte-use';

const drag = useDraggable(() => el, {
    axis: 'x',
    initialValue: { x: 100, y: 100 },
    onEnd: (pos) => console.log(pos)
});

drag.x(); // → number
drag.isDragging(); // → boolean
drag.style(); // → "transform: translate(100px, 0px);"

useElementSize

Reactively tracks element dimensions via ResizeObserver.

import { useElementSize } from '@ariefsn/svelte-use';

const size = useElementSize(() => el);
size.width(); // → number
size.height(); // → number

useIntersectionObserver

Viewport visibility detection.

import { useIntersectionObserver } from '@ariefsn/svelte-use';

const { isIntersecting, stop } = useIntersectionObserver(() => el, { threshold: 0.5 });
isIntersecting(); // → boolean

useResizeObserver

Raw ResizeObserver wrapper with automatic cleanup.

import { useResizeObserver } from '@ariefsn/svelte-use';

const { stop } = useResizeObserver(
    () => el,
    (entry) => {
        console.log(entry.contentRect.width);
    }
);

useMutationObserver

Observes DOM mutations on any node.

import { useMutationObserver } from '@ariefsn/svelte-use';

const { stop } = useMutationObserver(
    () => el,
    (mutations) => {
        for (const m of mutations) console.log(m.type);
    },
    { childList: true, subtree: true }
);

useIdle

Detect user inactivity.

import { useIdle } from '@ariefsn/svelte-use';

const { isIdle, reset } = useIdle(5000); // idle after 5s
isIdle(); // → boolean

useNetwork

Reactive Network Information API.

import { useNetwork } from '@ariefsn/svelte-use';

const net = useNetwork();
net.effectiveType(); // → '4g' | '3g' | undefined
net.downlink(); // → Mbps | undefined
net.saveData(); // → boolean | undefined

useGeolocation

Reactive geolocation via watchPosition.

import { useGeolocation } from '@ariefsn/svelte-use';

const geo = useGeolocation({ enableHighAccuracy: true });
geo.coords()?.latitude; // → number | null
geo.error(); // → GeolocationPositionError | null
geo.isSupported(); // → boolean

useFetch

Reactive fetch wrapper with loading/error state.

import { useFetch } from '@ariefsn/svelte-use';

const { data, loading, error, execute } = useFetch<User[]>('/api/users');
// data() → User[] | null
// loading() → boolean
// error() → Error | null

useWebSocket

Reactive WebSocket with auto-reconnect.

import { useWebSocket } from '@ariefsn/svelte-use';

const ws = useWebSocket('wss://echo.example.com');
ws.send('hello');
ws.data(); // → last received message
ws.status(); // → 'OPEN' | 'CLOSED' | 'CONNECTING'

useAnimate

Reactive Web Animations API wrapper.

import { useAnimate } from '@ariefsn/svelte-use';

const { animate, stop } = useAnimate(() => el);
animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300 });

useParallax

Parallax effect based on pointer position or device tilt.

import { useParallax } from '@ariefsn/svelte-use';

const { tilt, roll } = useParallax(() => containerEl);
// tilt() → number  (−0.5 to 0.5)
// roll() → number  (−0.5 to 0.5)

useTransition

Animated numeric transitions with easing.

import { useTransition } from '@ariefsn/svelte-use';

let target = $state(0);
const animated = useTransition(() => target, { duration: 500 });
// animated() smoothly interpolates to target

useInterval

Reactive interval counter.

import { useInterval } from '@ariefsn/svelte-use';

const { counter, pause, resume } = useInterval(1000);
counter(); // → increments every second

useNow

Reactive current Date.

import { useNow } from '@ariefsn/svelte-use';

const now = useNow();
now(); // → Date (updated every second by default)

useTimestamp

Reactive current timestamp in milliseconds.

import { useTimestamp } from '@ariefsn/svelte-use';

const ts = useTimestamp();
ts(); // → number (ms since epoch)

useBreakpoints

Reactive responsive breakpoints.

import { useBreakpoints } from '@ariefsn/svelte-use';

const bp = useBreakpoints({ sm: 640, md: 768, lg: 1024 });
bp.lg(); // → true if viewport ≥ 1024px
bp.between('sm', 'lg')(); // → boolean

useClipboard

Reactive clipboard read/write.

import { useClipboard } from '@ariefsn/svelte-use';

const { text, copy, copied } = useClipboard();
copy('Hello!');
copied(); // → true for 1.5s after copy

useBattery

Reactive Battery Status API.

import { useBattery } from '@ariefsn/svelte-use';

const battery = useBattery();
battery.level(); // → 0–1
battery.charging(); // → boolean

useVirtualList

Efficient virtual list rendering for large datasets.

import { useVirtualList } from '@ariefsn/svelte-use';

const { list, containerProps, wrapperProps } = useVirtualList(items, { itemHeight: 40 });
// list() → only the visible slice of items

Developing

bun install
bun run dev

To run tests:

bun run test

Building & Publishing

# build the library
bun run build

# publish to npm
npm publish --access public

Star History

Star History Chart

License

MIT

版本与发布记录

@ariefsn/svelte-use 共发布 4 个版本,首次发布于 2026/02/28;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.2.1latest2026/09/281 个月前
1.2.02026/09/271 个月前
1.1.02026/03/187 个月前
1.0.02026/02/288 个月前

关于 @ariefsn/svelte-use 的常见问题

@ariefsn/svelte-use 是什么?

Collection of reactive utility composables for Svelte 5 inspired by VueUse.

如何安装 @ariefsn/svelte-use?

在项目目录运行 npm install @ariefsn/svelte-use,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:svelte(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ariefsn/svelte-use 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ariefsn/svelte-use 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@ariefsn/svelte-use 可以商用吗?

@ariefsn/svelte-use 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ariefsn/svelte-use 的下载量有多少?

根据 npm 官方下载统计,@ariefsn/svelte-use 在 2026/10/07 – 2026/11/05 这 30 天内被下载 1,904 次,日均约 63 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ariefsn/svelte-use 还在维护吗?

最新版本 1.2.1 发布于 2026/09/28(1 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/02/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。