Skip to content

Instantly share code, notes, and snippets.

@Himenon
Last active March 26, 2019 10:41
Show Gist options
  • Save Himenon/8bac87738ea934983a9193d21c044871 to your computer and use it in GitHub Desktop.
Save Himenon/8bac87738ea934983a9193d21c044871 to your computer and use it in GitHub Desktop.
Resize Event React hook
type OnResizeFunction = (size: { width: number; height: number }) => void;
export const useOnResize = <T extends React.MutableRefObject<any | null>>(ref: T, onResize: OnResizeFunction) => {
React.useEffect(() => {
const callback = () => {
if (ref.current) {
onResize({
width: ref.current.clientWidth,
height: ref.current.clientHeight,
});
}
};
callback();
if (typeof window !== "undefined") {
window.addEventListener("resize", callback);
}
return () => {
if (typeof window !== "undefined") {
window.removeEventListener("resize", callback);
}
};
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment