useDevicePixelRatio.tsx 965 B

1234567891011121314151617181920212223242526272829303132
  1. import {useCallback, useLayoutEffect, useState} from 'react';
  2. /**
  3. * Hook to retrieve dpr value of the device and monitor for changes
  4. * (e.g. if user drags window to a screen with different dpr, we want to be notified).
  5. * @returns dpr of the device
  6. */
  7. function useDevicePixelRatio(): number {
  8. const [devicePixelRatio, setDevicePixelRatio] = useState<number>(
  9. window.devicePixelRatio
  10. );
  11. const updateDevicePixelRatio = useCallback(() => {
  12. setDevicePixelRatio(window.devicePixelRatio);
  13. }, []);
  14. useLayoutEffect(() => {
  15. window
  16. .matchMedia(`(resolution: ${devicePixelRatio}dppx)`)
  17. .addEventListener('change', updateDevicePixelRatio, {once: true});
  18. return () => {
  19. window
  20. .matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`)
  21. .removeEventListener('change', updateDevicePixelRatio);
  22. };
  23. }, [devicePixelRatio, updateDevicePixelRatio]);
  24. return devicePixelRatio;
  25. }
  26. export {useDevicePixelRatio};