I am trying to implement hook that would return offsetTop of an element. This is needed to apply some styles to header it sticks to top.
import { useState, useEffect } from 'react';
interface ElementPosition {
left: number | undefined;
right: number | undefined;
top: number | undefined;
bottom: number | undefined;
}
export const useElementPosition = (ref: any): ElementPosition => {
const [position, setPosition] = useState<ElementPosition>({
left: undefined,
right: undefined,
top: undefined,
bottom: undefined,
});
useEffect(() => {
if (ref.current) {
setPosition({
top: ref.current.offsetTop,
bottom: ref.current.offsetBottom,
left: ref.current.offsetLeft,
right: ref.current.offsetRight,
});
}
}, [ref.current]);
return position;
};
But now I remembered that ref.current change does not trigger useEffect so I am able to get initial offset only. Is there any way to do this in reusable way like hooks?