From c9abcb0bb1a18ac07a0b2c2279dffd9eb2bb4f32 Mon Sep 17 00:00:00 2001 From: No0ne003 Date: Tue, 7 May 2024 13:58:14 +0100 Subject: [PATCH] useWindowResize Custom hook --- .../CustomHooks/use-window-resize/test.jsx | 23 +++++++++++++--- .../use-window-resize/useWindowResize.jsx | 27 +++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/src/pages/CustomHooks/use-window-resize/test.jsx b/src/pages/CustomHooks/use-window-resize/test.jsx index bbb81e6..b1571bf 100644 --- a/src/pages/CustomHooks/use-window-resize/test.jsx +++ b/src/pages/CustomHooks/use-window-resize/test.jsx @@ -1,5 +1,22 @@ +import useWindowResize from "./useWindowResize"; + export const UseWindowResizeTest = () => { + const windowSize = useWindowResize(); + const { width, height } = windowSize; + return ( -
UseWindowResizeTest
- ) -} +
+

+ useWindow resize Hook +

+
+

+ Width is {width} +

+

+ Height is {height} +

+
+
+ ); +}; diff --git a/src/pages/CustomHooks/use-window-resize/useWindowResize.jsx b/src/pages/CustomHooks/use-window-resize/useWindowResize.jsx index e69de29..f6402ba 100644 --- a/src/pages/CustomHooks/use-window-resize/useWindowResize.jsx +++ b/src/pages/CustomHooks/use-window-resize/useWindowResize.jsx @@ -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; +}