index.js
40 lines
| 1 | import {useState, useEffect} from 'react'; |
| 2 | import {useSelector} from 'react-redux'; |
| 3 | |
| 4 | // From use hooks, see: https://usehooks.com/useWindowSize/ |
| 5 | |
| 6 | export const useAccentColor = () => { |
| 7 | return useSelector((state) => state.accentColor); |
| 8 | }; |
| 9 | |
| 10 | export const useWindowSize = () => { |
| 11 | // Initialize state with undefined width/height so server and client renders match |
| 12 | // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/ |
| 13 | const [windowSize, setWindowSize] = useState({ |
| 14 | width: undefined, |
| 15 | height: undefined, |
| 16 | }); |
| 17 | |
| 18 | useEffect(() => { |
| 19 | // Handler to call on window resize |
| 20 | function handleResize() { |
| 21 | // Set window width/height to state |
| 22 | setWindowSize({ |
| 23 | width: window.top.innerWidth, |
| 24 | height: window.top.innerHeight, |
| 25 | }); |
| 26 | } |
| 27 | |
| 28 | // Add event listener |
| 29 | window.top.addEventListener('resize', handleResize); |
| 30 | |
| 31 | // Call handler right away so state gets updated with initial window size |
| 32 | handleResize(); |
| 33 | |
| 34 | // Remove event listener on cleanup |
| 35 | return () => window.top.removeEventListener('resize', handleResize); |
| 36 | }, []); // Empty array ensures that effect is only run on mount |
| 37 | |
| 38 | return windowSize; |
| 39 | }; |
| 40 |