useScrollToTop.tsx 785 B

12345678910111213141516171819202122232425262728293031
  1. import {useEffect, useRef} from 'react';
  2. import {Location} from 'history';
  3. type Options = {
  4. location: Location;
  5. /**
  6. * Function to stop scrolling from happening if a certan condition is met
  7. */
  8. disable?: (location: Location, prevLocation: Location) => boolean;
  9. };
  10. /**
  11. * Automatically scrolls to the top of the page any time the location changes.
  12. */
  13. function useScrollToTop({location, disable}: Options) {
  14. const lastLocation = useRef(location);
  15. // Check if we should scroll to the top any time the location changes
  16. useEffect(() => {
  17. const shouldDisable = disable?.(location, lastLocation.current);
  18. lastLocation.current = location;
  19. if (shouldDisable) {
  20. return;
  21. }
  22. window.scrollTo(0, 0);
  23. }, [location]);
  24. }
  25. export default useScrollToTop;