UNPKG

@jjordy/swr-devtools

Version:

Devtools for SWR

56 lines (55 loc) 1.72 kB
import React, { useEffect, useRef } from "react"; const events = new Set(); const onResize = () => events.forEach((fn) => fn()); export function useWindowSize(options = {}) { const { throttleMs = 100 } = options; const [size, setSize] = React.useState({ width: typeof window !== "undefined" ? window.innerWidth : 0, height: typeof window !== "undefined" ? window.innerHeight : 0, }); const handle = throttle(() => { setSize({ width: window.innerWidth, height: window.innerHeight, }); }, throttleMs); useEffect(() => { if (events.size === 0) { window.addEventListener("resize", onResize, true); } events.add(handle); return () => { events.delete(handle); if (events.size === 0) { window.removeEventListener("resize", onResize, true); } }; }, []); return size; } export function throttle(func, threshold = 250, scope) { let last, deferTimer; return function () { let context = scope || this; let now = Date.now(), args = arguments; if (last && now < last + threshold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; func.apply(context, args); }, threshold); } else { last = now; func.apply(context, args); } }; } export function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; }