onScroll is a React event triggered when a user scrolls an element or the window, enabling tracking of scroll position and dynamic UI updates.
Triggered on Scroll: Fires when scrolling occurs on an element or window.
Track Position: Used to monitor scroll position.
Infinite Scrolling: Helps load more content dynamically.
Lazy Loading: Loads content only when it enters the viewport.
UI Updates: Enables effects like sticky headers or animations.
Syntax:
<element onScroll={handlerFunction} />
element: The JSX element (e.g., <div>, <section>, or <body>) to which the scroll event is attached.
onScroll: The event handler prop in camelCase.
handlerFunction: The function that will be called whenever the scroll event is triggered.
Working
The onScroll event in React is triggered whenever the user scrolls an element (like a div) or the window. It helps track how far the user has scrolled.
1. Triggered on Scroll: The onScroll event is fired when the user scrolls an element or the window.
2. Access Scroll Properties: Inside the event handler, you can access the following properties:
scrollTop: The number of pixels the content has been scrolled.
scrollHeight: The total height of the content inside the scrollable area.
clientHeight: The visible height of the scrollable element.
Example 1: Basic implementation of onScroll() event to get the scroll position.
Output:
Example 2: Basic implementation of onScroll() event to change the background color according to scroll position.
Note: It is similar to the HTML DOM onscroll event but uses the camelCase convention in React.
Best Practices
Handling the onScroll event in React is straightforward, but to ensure smooth performance and a better user experience, there are a few best practices you should follow.
Avoid Direct DOM Manipulation: Always use React state instead of directly manipulating the DOM. This keeps your app efficient.
Update State Only When Needed: Don’t update the state on every scroll event. Only update it when necessary to avoid performance issues.
Optimize Re-renders: Use React.memo or useMemo to prevent unnecessary re-renders when only the scroll data changes.
Track Scroll Using Relevant Properties: Use scrollTop, scrollHeight, and clientHeight to calculate the scroll position and handle logic like infinite scroll or sticky elements.