Skip to content

Instantly share code, notes, and snippets.

@jonahallibone
Created May 28, 2019 16:41
Show Gist options
  • Save jonahallibone/0630f5763af50c836496607fa16e526e to your computer and use it in GitHub Desktop.
Save jonahallibone/0630f5763af50c836496607fa16e526e to your computer and use it in GitHub Desktop.
Hook for scroll to top
import React, { useEffect, useRef } from "react";
import { withRouter } from 'react-router-dom';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
})
return ref.current;
}
const ScrollToTop = (props) => {
const { location } = props;
const prevProps = usePrevious({location});
useEffect(() => {
if(!prevProps) return;
if (location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0);
}
}, [location]);
return (
<div></div>
)
}
export default withRouter(ScrollToTop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment