You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829
  1. import React, {useState, useEffect} from "react";
  2. const useWindowSize = () => {
  3. // Initialize state with undefined width/height so server and client renders match
  4. const [windowSize, setWindowSize] = useState({
  5. width: undefined,
  6. height: undefined,
  7. });
  8. useEffect(() => {
  9. // Handler to call on window resize
  10. function handleResize() {
  11. // Set window width/height to state
  12. setWindowSize({
  13. width: window.innerWidth,
  14. height: window.innerHeight,
  15. });
  16. }
  17. // Add event listener
  18. window.addEventListener("resize", handleResize);
  19. // Call handler right away so state gets updated with initial window size
  20. handleResize();
  21. // Remove event listener on cleanup
  22. return () => window.removeEventListener("resize", handleResize);
  23. }, []); // Empty array ensures that effect is only run on mount
  24. return windowSize;
  25. }
  26. export default useWindowSize;