Skip to content

Instantly share code, notes, and snippets.

@designbyadrian
Last active September 2, 2020 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designbyadrian/9de2698a17eb1c9f0fe61026262c11de to your computer and use it in GitHub Desktop.
Save designbyadrian/9de2698a17eb1c9f0fe61026262c11de to your computer and use it in GitHub Desktop.
For when you otherwise would try multiple dynamic refs.
import {useLayoutEffect, useRef} from 'react';
export default ({onChange}) => {
const myRef = useRef();
const updatePosition = () => {
const rect = myRef.current.getBoundingClientRect();
onChange(rect);
};
useLayoutEffect(() => {
window.addEventlistener('scroll', updatePosition);
window.addEventlistener('resize', updatePosition);
return () => {
window.removeEventlistener('scroll', updatePosition);
window.removeEventlistener('resize', updatePosition);
};
}, []);
return <div ref={myRef} />
}
import {useRef} from 'react';
import Child from './Child';
export default () => {
const tempStore = useRef([]);
const debouncedOrThrottledFunction = () => {
const positions = [...tempStore.current];
tempStore.current = [];
// do something with the collection of positions
}
const handleChildUpdate = position => {
tempStore.current.push(position);
debouncedOrThrottledFunction()
}
return (
<>
{arrayOfSomeSort.map(child => (
<Child onChange={handleChildUpdate} />
))}
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment