Skip to content

Instantly share code, notes, and snippets.

@kevinfelisilda
Created April 7, 2019 09:52
Show Gist options
  • Save kevinfelisilda/fce9e14f8c155728274ba2daf04a7387 to your computer and use it in GitHub Desktop.
Save kevinfelisilda/fce9e14f8c155728274ba2daf04a7387 to your computer and use it in GitHub Desktop.
hook for triggering callback on browser resize
import { useEffect, useState } from 'react';
/**
* Usage:
*
* const ref = useRef();
*
* useResize(ref, (data) => {
* console.log(data.width);
* });
*
* return (
* <div ref={ref}>
* The content
* </div>
* );
*/
const useResize = (ref, callback, defaultValue = {}) => {
const [initialize, setInitialized] = useState(false);
const getValue = () => {
const target = ref && ref.current;
if (!target) {
return defaultValue;
}
return {
height: target.offsetHeight,
width: target.offsetWidth,
x: target.offsetLeft,
y: target.offsetTop,
target
};
}
const onResize = () => {
if ('function' === typeof callback) {
callback(getValue());
}
}
useEffect(() => {
window.addEventListener('resize', onResize);
if (!initialize) {
onResize();
setInitialized(true);
}
return () => {
window.removeEventListener('resize', onResize);
}
})
}
export const useResize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment