Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. function useWindowSize() {
  2. // save in instance memory: [{ windowHeight, windowWidth }]
  3. const [{ windowWidth, windowHeight }, setWindowSize] = useState({
  4. windowWidth: window.innerWidth,
  5. windowHeight: window.innerHeight
  6. });
  7.  
  8. // This will run after every render
  9. useEffect(() => {
  10. // Set new state
  11. const handleResize = () =>
  12. setWindowSize({
  13. windowWidth: window.innerWidth,
  14. windowHeight: window.innerHeight
  15. });
  16.  
  17. window.addEventListener("resize", handleResize);
  18.  
  19. // The "cleanup" function
  20. return () =>
  21. window.removeEventListener("resize", handleResize);
  22. };
  23. });
  24.  
  25. return { windowHeight, windowWidth };
  26. }
  27.  
  28. function WindowSize() {
  29. const { windowWidth, windowHeight } = useWindowSize();
  30.  
  31. return (
  32. <p> The window is { windowWidth } x { windowHeight } </p>
  33. );
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement