Skip to content

Instantly share code, notes, and snippets.

@Ricaidito
Created December 25, 2022 16:48
Show Gist options
  • Save Ricaidito/62a0446016c8d6e8545553b3f131854c to your computer and use it in GitHub Desktop.
Save Ricaidito/62a0446016c8d6e8545553b3f131854c to your computer and use it in GitHub Desktop.
Custom React hook to detect if the screen width is within the specified bounds
import { useEffect, useState } from "react";
const defaultSize = 640;
export const useScreenSize = (sizeToCheck = defaultSize) => {
const [sizeOnBounds, setSizeOnBounds] = useState(
window.innerWidth <= sizeToCheck
);
const sizeChecker = () => {
setSizeOnBounds(window.innerWidth <= sizeToCheck);
};
useEffect(() => {
window.addEventListener("resize", sizeChecker);
return () => window.removeEventListener("resize", sizeChecker);
});
return sizeOnBounds;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment