Created
December 25, 2022 16:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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