import { useEffect , useLayoutEffect } from 'react' ; export interface IScrollState { scrollTop : number ; scrollLeft : number ; } export function useControlledScroll ( element , state ) { useEffect ( ( ) => { const box = element ; if ( box ) { box . scrollTop = state . scrollTop ; box . scrollLeft = state . scrollLeft ; } } , [ element , state ] ) ; useLayoutEffect ( ( ) => { const box = element ; if ( ! box ) { return ; } const handleScroll = ( ) => { if ( box ) { state . scrollTop = box . scrollTop ; state . scrollLeft = box . scrollLeft ; } } ; box . addEventListener ( 'scroll' , handleScroll ) ; return ( ) => box . removeEventListener ( 'scroll' , handleScroll ) ; } , [ element , state ] ) ; }