1.0.2 • Published 3 years ago

@enjoywater-hook/use-keep-scroll v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

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

  1. Add import useKeepScroll from "@enjoywater-hook/use-keep-scroll" in your component.
  2. Add a ref to the scrolling component.
  3. Put the ref component as an argument of useKeepScroll().
  4. 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;
1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago