Skip to content

Commit

Permalink
Merge pull request #249 from hugo-vrijswijk/fix-current-set
Browse files Browse the repository at this point in the history
Fix ref `.current` set by using a proxy
  • Loading branch information
snelsi authored Jan 4, 2024
2 parents 9f37f20 + a302cae commit 5996935
Showing 1 changed file with 30 additions and 11 deletions.
41 changes: 30 additions & 11 deletions src/useResizeDetector.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState, useRef, useCallback } from 'react';
import { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import type { DebouncedFunc } from 'lodash';

import { patchResizeCallback } from './utils';
Expand Down Expand Up @@ -42,18 +42,37 @@ function useResizeDetector<T extends HTMLElement = any>({
}, 0);
}

// this is a callback that will be called every time the ref is changed
// this is a memo that will be called every time the ref is changed
// This proxy will properly call setState either when the ref is called as a function or when `.current` is set
// we call setState inside to trigger rerender
const onRefChange: OnRefChangeType = useCallback(
(node: T | null) => {
if (node !== refElement) {
setRefElement(node);
}
},

const refProxy: OnRefChangeType<T> = useMemo(
() =>
new Proxy(
node => {
if (node !== refElement) {
setRefElement(node);
}
},
{
get(target, prop) {
if (prop === 'current') {
return refElement;
}
return target[prop];
},
set(target, prop, value) {
if (prop === 'current') {
setRefElement(value);
} else {
target[prop] = value;
}
return true;
}
}
),
[refElement]
);
// adding `current` to make it compatible with useRef shape
onRefChange.current = refElement;

const shouldSetSize = useCallback(
(prevSize: ReactResizeDetectorDimensions, nextSize: ReactResizeDetectorDimensions) => {
Expand Down Expand Up @@ -124,7 +143,7 @@ function useResizeDetector<T extends HTMLElement = any>({
onResize?.(size.width, size.height);
}, [size]);

return { ref: onRefChange, ...size };
return { ref: refProxy, ...size };
}

export default useResizeDetector;

0 comments on commit 5996935

Please sign in to comment.