Skip to content

Commit

Permalink
feat: useWindowSize hook
Browse files Browse the repository at this point in the history
  • Loading branch information
congweibai committed Aug 13, 2024
1 parent d23853e commit 9a01490
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export * from "./useHover/useHover";
export * from "./useFavicon/useFavicon";
export * from "./useQueue/useQueue";
export * from "./useTimeout";
export * from "./useWindowSize";
1 change: 1 addition & 0 deletions src/hooks/useWindowSize/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useWindowSize";
34 changes: 34 additions & 0 deletions src/hooks/useWindowSize/useWindowSize.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { renderHook, act } from "@testing-library/react-hooks";
import useWindowSize from "./useWindowSize";
import { describe, expect, it } from "vitest";

describe("useWindowSize", () => {
it("should return the initial window size", () => {
// mock
window.innerWidth = 1024;
window.innerHeight = 768;

// act
const { result } = renderHook(() => useWindowSize());

// assert
expect(result.current.width).toBe(1024);
expect(result.current.height).toBe(768);
});

it("should update the window size on resize", () => {
// mock
const { result } = renderHook(() => useWindowSize());

// act
act(() => {
window.innerWidth = 1280;
window.innerHeight = 720;
window.dispatchEvent(new Event("resize"));
});

// assert
expect(result.current.width).toBe(1280);
expect(result.current.height).toBe(720);
});
});
28 changes: 28 additions & 0 deletions src/hooks/useWindowSize/useWindowSize.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useLayoutEffect, useState } from "react";

export default function useWindowSize() {
const [size, setSize] = useState({
width: 0,
height: 0,
});

useLayoutEffect(() => {
const onResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight,
});
};

onResize();

window.addEventListener("resize", onResize);

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

return {
height: size.height,
width: size.width,
};
}

0 comments on commit 9a01490

Please sign in to comment.