I'm using React hooks useEffect to get the width and height of the container.
The problems I want to solve are:
window.innerHeight and this itself crashes my output on the Initial render as I'm using the dimension state to get something done in the first place.I'm new to this React Hooks and unaware of many things.. I want simple code which perfectly does the work.
My code is as below:
function debounce(fn, ms) {
let timer;
return (_) => {
clearTimeout(timer);
timer = setTimeout((_) => {
timer = null;
fn.apply(this, arguments);
}, ms);
};
}
export default function App() {
const [dimensions, setDimensions] = useState({
height: window.innerHeight,
width: window.innerWidth,
});
useEffect(() => {
const debouncedHandleResize = debounce(function handleResize() {
setDimensions({
height: window.innerHeight,
width: window.innerWidth,
});
}, 1000);
document
.getElementById('SldBox')
.addEventListener('resize', debouncedHandleResize);
return (_) => {
document
.getElementById('SldBox')
.removeEventListener('resize', debouncedHandleResize);
};
});
return (
<div className='container' id='SldBox'>
My Container
</div>
);
}
Cool problem, lots of hooks to be learned here.
Here is a sample of how we can use:
https://codesandbox.io/s/keen-poincare-c8mcz?file=/src/App.js
useState: You've made good use of this one. No need to explain it more.
useRef: Create a ref then pass it to your element.
export default function App() {
const ref = useRef(null);
return (
<div ref={ref}>stuff</div>
);
}
Now after the first render, we can reference the element easily enough.
useMemo: To set up an observer for an element we can use ResizeObserver. If we didn't wrap this in useMemo, we would be recreating this function on every render which is wasteful. useMemo remedies this. We also add a dependency array for useMemo as the second argument that includes ref.current. This way, anytime ref changes (like on the first render), the elementObserver function will be recalculated.
const elementObserver = useMemo(() => {
return new ResizeObserver(() => {
debounce(() => {
if (!ref.current) return;
setDimensions({
height: ref.current.clientHeight,
width: ref.current.clientWidth
});
}, 1000)();
});
}, [ref.current]);
useEffect: Now we can just use useEffect to set the observer when the component mounts. Again we include a dependency array that tells the effect to trigger the callback function provided if any of these values are changed. It will also always run when the component mounts, so we need to check ref exists for this one. Also, assign the element to a variable in the effect for the "cleanup" function.
useEffect(() => {
if (!ref) return;
const element = ref.current;
elementObserver.observe(element);
return () => {
elementObserver.unobserve(element);
};
}, [ref.current, elementObserver]);