@enjoywater-hook/use-keep-scroll
v1.0.2
Published
React hook to maintain scroll position using session storage when returning to the page.
Downloads
1
Maintainers
Readme
useKeepScroll
React hook to maintain scroll position using session storage when returning to the page.
📌
useKeepScroll is custom React-Hook. So it works on only React environment.
This hook maintains the scroll position of a specific component, not the window's scroll.
If you want to keep the scroll position of the window, see here.
🛠️ Installation
$ npm install @enjoywater-hook/use-keep-scroll
or
$ yarn add @enjoywater-hook/use-keep-scroll
🔍 Full Code
import { useEffect, useCallback } from 'react';
const useKeepScroll = (scrollRef) => {
const setScroll = useCallback(() => {
if (!scrollRef.current) return;
// Save the current scroll position of scrollRef in session storage.
sessionStorage.setItem('scrollY', `${scrollRef.current.scrollTop}`);
}, [scrollRef]);
useEffect(() => {
if (!scrollRef.current) return;
// Get the saved scroll position.
const scrollValue = sessionStorage.getItem('scrollY');
// Change the scroll position of scrollRef.
if (scrollValue) scrollRef.current.scrollTop = +scrollValue;
// When refreshing, the scroll value in the session storage is initialized.
const handleRefresh = () => sessionStorage.removeItem('scrollY');
window.addEventListener('beforeunload', handleRefresh);
return () => window.removeEventListener('beforeunload', handleRefresh);
}, [scrollRef]);
return setScroll;
};
export default useKeepScroll;
📝 How To Use
- Add
import useKeepScroll from "@enjoywater-hook/use-keep-scroll"
in your component. - Add a
ref
to the scrolling component. - Put the
ref
component as an argument ofuseKeepScroll()
. - Execute the returned
setScroll
function wherever you want.
🔍 Example
An example of maintaining the scroll position of the list screen when moving to a detail page.
import useKeepScroll from '@enjoywater-hook/use-keep-scroll';
function Component() {
const listRef = useRef(null);
const setScroll = useKeepScroll(listRef);
const handleItemClick = () => {
setScroll();
push('/detail');
};
return (
<div ref={listRef}>
<ul>
<li onClick={handleItemClick}>...</li>
...
</ul>
</div>
);
}
export default Component;