Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Resolve the error coming up during local project setup #56

Merged
merged 2 commits into from
Aug 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 23 additions & 34 deletions hooks/useWindowDimensions.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,34 @@
import { useState, useEffect } from 'react';

function debounce(fn, ms) {
let timer;
return _ => {
clearTimeout(timer);
timer = setTimeout(_ => {
timer = null;
fn.apply(this, ...arguments);
}, ms);
};
}
const initDimensions = {
height: 0,
width: 0,
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The initDimensions object is a good addition. This ensures initial state is predictable.


export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState({
width: undefined,
height: undefined,
});
function getWindowDimensions(hasWindow) {
const width = hasWindow ? window.innerWidth : null;
const height = hasWindow ? window.innerHeight : null;
return {
width,
height,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the useWindowDimensions function, you don't need to pass hasWindow to getWindowDimensions since it's already defined inside useEffect. The hasWindow check can just be used directly.

};
}

const [windowDimensions, setWindowDimensions] = useState(initDimensions);

useEffect(() => {
const debouncedHandleResize = debounce(
const hasWindow = typeof window !== 'undefined';
if (hasWindow) {
function handleResize() {
setWindowDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
},
0
);

window.addEventListener(
'resize',
debouncedHandleResize,
{
passive: true,
setWindowDimensions(getWindowDimensions(hasWindow));
}
);
return () =>
window.removeEventListener(
'resize',
debouncedHandleResize
);

// Gets window size for the first time
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}
}, []);

return windowDimensions;
Expand Down