Last active
September 2, 2020 17:06
-
-
Save designbyadrian/9de2698a17eb1c9f0fe61026262c11de to your computer and use it in GitHub Desktop.
For when you otherwise would try multiple dynamic refs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} /> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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