diff --git a/package.json b/package.json index ca355c8..00a5d12 100644 --- a/package.json +++ b/package.json @@ -104,6 +104,7 @@ "webpack": "^4.43.0" }, "dependencies": { - "debounce": "^1.2.0" + "debounce": "^1.2.0", + "rafz": "^0.1.14" } } diff --git a/src/web/index.ts b/src/web/index.ts index 6b43339..62c766c 100644 --- a/src/web/index.ts +++ b/src/web/index.ts @@ -1,5 +1,6 @@ import { useEffect, useState, useRef, useMemo } from 'react' import { debounce as createDebounce } from 'debounce' +import { raf } from 'rafz' declare type ResizeObserverCallback = (entries: any[], observer: ResizeObserver) => void declare class ResizeObserver { @@ -76,6 +77,10 @@ function useMeasure({ debounce, scroll, polyfill }: Options = { debounce: 0, scr // memoize handlers, so event-listeners know when they should update const [forceRefresh, resizeChange, scrollChange] = useMemo(() => { + const setState = () => { + set(state.current.lastBounds) + } + const callback = () => { if (!state.current.element) return const { @@ -90,8 +95,13 @@ function useMeasure({ debounce, scroll, polyfill }: Options = { debounce: 0, scr } = (state.current.element.getBoundingClientRect() as unknown) as RectReadOnly const size = { left, top, width, height, bottom, right, x, y } Object.freeze(size) - if (mounted.current && !areBoundsEqual(state.current.lastBounds, size)) set((state.current.lastBounds = size)) + + if (mounted.current && !areBoundsEqual(state.current.lastBounds, size)) { + state.current.lastBounds = size + raf.write(setState) + } } + return [ callback, resizeDebounce ? createDebounce(callback, resizeDebounce) : callback, diff --git a/yarn.lock b/yarn.lock index 08273c5..10bf213 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5502,6 +5502,11 @@ querystring@0.2.0: resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" integrity sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA= +rafz@^0.1.14: + version "0.1.14" + resolved "https://registry.yarnpkg.com/rafz/-/rafz-0.1.14.tgz#164f01cf7cc6094e08467247ef351ef5c8d278fe" + integrity sha512-YiQkedSt1urYtYbvHhTQR3l67M8SZbUvga5eJFM/v4vx/GmDdtXlE2hjJIyRjhhO/PjcdGC+CXCYOUA4onit8w== + randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.5, randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"