useWindowSize
hookas/use-window-sizeFreeHook
A hook to get the window size
Install it
npx shadcn@latest add https://hookas.letstri.dev/r/use-window-size.jsonSource
1'use client'23import * as React from 'react'45interface WindowSize {6 width: number7 height: number8}910export function useWindowSize(): WindowSize {11 const windowSizeSubscriber = React.useCallback((callback: () => void) => {12 const abortController = new AbortController()1314 window.addEventListener('resize', callback, { signal: abortController.signal })1516 return () => {17 abortController.abort()18 }19 }, [])2021 const getSnapshot = React.useCallback(() => {22 return {23 width: typeof window !== 'undefined' ? window.innerWidth : 0,24 height: typeof window !== 'undefined' ? window.innerHeight : 0,25 }26 }, [])2728 const getServerSnapshot = React.useCallback(() => {29 return {30 width: 0,31 height: 0,32 }33 }, [])3435 const windowSize = React.useSyncExternalStore(36 windowSizeSubscriber,37 getSnapshot,38 getServerSnapshot,39 )4041 return windowSize42}
Files it writes
More from hookas
All 30 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAsyncEffectuse-async-effect | hookas | Hooks | Free | no deps | |
| useClickOutsideuse-click-outside | hookas | Hooks | Free | no deps | |
| useDebounceCallbackuse-debounced-callback | hookas | Hooks | Free | no deps | |
| useDebounceMemouse-debounced-memo | hookas | Hooks | Free | no deps | |
| useDebounceStateuse-debounced-state | hookas | Hooks | Free | no deps | |
| useElementSizeuse-element-size | hookas | Hooks | Free | no deps | |
| useFullscreenuse-fullscreen | hookas | Hooks | Free | no deps | |
| useIntervaluse-interval | hookas | Hooks | Free | no deps |
