Skip to content

Commit

Permalink
fix: useSize error ResizeObserver loop limit exceeded
Browse files Browse the repository at this point in the history
  • Loading branch information
brickspert committed Jul 22, 2021
1 parent abfce57 commit b8e7542
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
8 changes: 5 additions & 3 deletions packages/hooks/src/useSize/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useState, useLayoutEffect } from 'react';
import { useLayoutEffect } from 'react';
import ResizeObserver from 'resize-observer-polyfill';
import { getTargetElement, BasicTarget } from '../utils/dom';
import type { BasicTarget } from '../utils/dom';
import { getTargetElement } from '../utils/dom';
import useRafState from './useRafState';

type Size = { width?: number; height?: number };

function useSize(target: BasicTarget): Size {
const [state, setState] = useState<Size>(() => {
const [state, setState] = useRafState<Size>(() => {
const el = getTargetElement(target);
return {
width: ((el || {}) as HTMLElement).clientWidth,
Expand Down
24 changes: 24 additions & 0 deletions packages/hooks/src/useSize/useRafState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { Dispatch, SetStateAction } from 'react';
import { useCallback, useRef, useState } from 'react';
import useUnmount from '../useUnmount';

const useRafState = <S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>] => {
const frame = useRef(0);
const [state, setState] = useState(initialState);

const setRafState = useCallback((value: S | ((prevState: S) => S)) => {
cancelAnimationFrame(frame.current);

frame.current = requestAnimationFrame(() => {
setState(value);
});
}, []);

useUnmount(() => {
cancelAnimationFrame(frame.current);
});

return [state, setRafState];
};

export default useRafState;

0 comments on commit b8e7542

Please sign in to comment.