Complete Guide to Getting and Restoring Scroll Position in React

Nov 23, 2025 · Programming · 6 views · 7.8

Keywords: React scroll position | window.pageYOffset | useEffect listening

Abstract: This article provides a comprehensive exploration of accurately obtaining and restoring page scroll positions in React applications. By analyzing the usage of window.pageYOffset property, implementation of scroll event listeners, and differences between useEffect and useLayoutEffect, it offers a complete scroll position management solution with detailed code examples and best practices.

Fundamental Principles of Scroll Position Retrieval

In web development, retrieving page scroll position is a common requirement. React applications can track user scrolling behavior in real-time by listening to scroll events. The window.pageYOffset property returns the number of pixels the document has been scrolled vertically from the top, providing the most direct method for obtaining scroll position.

When users click on items in a list to view details, we need to record the current scroll position to enable accurate return to the previous position after closing the details. This involves coordination between state management and event handling.

Implementing Scroll Listening with React Hooks

Modern React applications recommend using Hooks for state and side effect management. Here's a complete scroll position listening implementation:

import React, { useState, useEffect } from 'react';

const ScrollPositionTracker = () => {
  const [scrollYPosition, setScrollYPosition] = useState(0);
  
  const handleScroll = () => {
    const newScrollYPosition = window.pageYOffset;
    setScrollYPosition(newScrollYPosition);
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div>
      <p>Current scroll position: {scrollYPosition}px</p>
    </div>
  );
};

export default ScrollPositionTracker;

In this implementation, useEffect adds the scroll event listener when the component mounts and cleans up when the component unmounts, preventing memory leaks. The empty dependency array ensures the effect runs only on mount and unmount.

Saving Scroll Position on Click Events

When users click list items to view details, we need to save the current scroll position:

inSingle = (post, e) => {
  this.setState({
    post: post,
    theposition: window.pageYOffset
  });
  window.scrollTo(0, 0);
}

This directly uses window.pageYOffset to get the current scroll position, saves it to state, then scrolls to the top of the page to display detail content.

Implementing Scroll Position Restoration

When closing the detail page, use the saved position to restore scrolling:

closeDetail = () => {
  this.setState({
    post: null
  });
  window.scrollTo(0, this.state.theposition);
}

This approach ensures users can accurately return to their previous browsing position, providing a smooth user experience.

Alternative Approach with useLayoutEffect

In some cases, useLayoutEffect can be used for more immediate response to layout changes:

import React, { useLayoutEffect, useState } from 'react';

export default function useWindowPosition() {
  const [scrollPosition, setPosition] = useState(0);
  
  useLayoutEffect(() => {
    function updatePosition() {
      setPosition(window.pageYOffset);
    }
    
    window.addEventListener('scroll', updatePosition);
    updatePosition();
    
    return () => window.removeEventListener('scroll', updatePosition);
  }, []);
  
  return scrollPosition;
}

useLayoutEffect executes synchronously before browser paint, making it suitable for scenarios requiring immediate layout information reading.

Performance Optimization Considerations

Scroll events can fire frequently, requiring performance optimization considerations:

Browser Compatibility

window.pageYOffset is well-supported in modern browsers and serves as an alias for window.scrollY. For older browsers, document.documentElement.scrollTop or document.body.scrollTop can be used as fallback options.

Extended Practical Application Scenarios

This scroll position management technique can extend to various scenarios:

By properly applying these techniques, you can significantly enhance the interactive experience and user satisfaction of React applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.