I create simple custom hook that save the screen height and width . The problem is that I want to re-render(update state) only if some condition in my state is happened and not in every resize event.. I try first with simple implementation :
const useScreenDimensions = () => {
const [height, setHeight] = useState(window.innerWidth);
const [width, setWidth] = useState(window.innerHeight);
const [sizeGroup, setSizeGroup]useState(getSizeGroup(window.innerWidth));
useEffect(() => {
const updateDimensions = () => {
if (getSizeGroup() !== sizeGroup) {
setSizeGroup(getSizeGroup(width));
setHeight(window.innerHeight);
setWidth(window.innerWidth);
}
};
window.addEventListener('resize', updateDimensions);
return () => window.removeEventListener('resize', updateDimensions);
}, [sizeGroup, width]);
return { height, width };
}
The problem with this approach is that the effect calls every time , I want that the effect will call just once without dependencies (sizeGroup, width) because I don't want to register the event every time there is a change in screen width/size group(window.addEventListener).
So, I try with this approach with UseCallBack , but also here my 'useEffect' function called many times every time there is any change in the state..
//useState same as before..
const updateDimensions = useCallback(() => {
if (getSizeGroup(window.innerWidth) !== sizeGroup) {
setSizeGroup(getSizeGroup(width));
setHeight(window.innerHeight);
setWidth(window.innerWidth);
}
}, [sizeGroup, width]);
useEffect(() => {
window.addEventListener('resize', updateDimensions);
return () => window.removeEventListener('resize', updateDimensions);
}, [updateDimensions]);
....
return { height, width };
The question is what the correct and effective way for my purposes? I want just "register" the event once, and update the my state only when my state variable is true and not every time the width or something else get updated..
I know that when you set empty array as second argument to 'UseEffect' it's run only once but in my case I want that the register of my event listener run once and on resize I will update the state only if some condition is true
Thanks a lot.