Skip to content

Commit

Permalink
useWindowResize Custom hook
Browse files Browse the repository at this point in the history
  • Loading branch information
No0ne003 committed May 7, 2024
1 parent d511122 commit c9abcb0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/pages/CustomHooks/use-window-resize/test.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import useWindowResize from "./useWindowResize";

export const UseWindowResizeTest = () => {
const windowSize = useWindowResize();
const { width, height } = windowSize;

return (
<div>UseWindowResizeTest</div>
)
}
<div className="flex justify-center items-center h-screen flex-col gap-4">
<h1 className="text-3xl">
<span className="font-bold text-primary">useWindow</span> resize Hook
</h1>
<div>
<p>
Width is <span className="font-bold">{width}</span>
</p>
<p>
Height is <span className="font-bold">{height}</span>
</p>
</div>
</div>
);
};
27 changes: 27 additions & 0 deletions src/pages/CustomHooks/use-window-resize/useWindowResize.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useLayoutEffect, useState } from "react";

export default function useWindowResize() {
const [windowSize, setWindowSize] = useState({
width: 0,
height: 0,
});

function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}

useLayoutEffect(() => {
handleResize();

window.addEventListener("resize", handleResize);

return () => {
window.removeEventListener("resize", handleResize);
};
}, []);

return windowSize;
}

0 comments on commit c9abcb0

Please sign in to comment.