React Reference ยท Props and Attributes
React onScroll and onWheel props
How onScroll and onWheel work in React: reading scrollTop and deltaY, why scroll does not bubble, passive wheel listeners and performance tips.
onScroll fires on an element whose scroll position changed. onWheel fires when the mouse wheel (or a trackpad gesture) turns over an element, whether or not anything actually scrolls. They are related but separate: wheel input can cause scrolling, but scrolling also happens through the keyboard, scrollbar drags and touch.
Read the position from the element with event.currentTarget.scrollTop, and the wheel movement from event.deltaY.
<div onScroll={(e) => setTop(e.currentTarget.scrollTop)}>...</div> <div onWheel={(e) => console.log(e.deltaY)}>...</div>
Try it
onWheel reports direction and distance, in deltaY (vertical) and deltaX (horizontal). Positive deltaY means scrolling down.
Syntax
<element onScroll={(event: React.UIEvent) => { ... }} /> <element onWheel={(event: React.WheelEvent) => { ... }} />
| Name | Description |
|---|---|
event.currentTarget.scrollTop / scrollLeft |
The current scroll offset of the element. |
scrollHeight, clientHeight |
Total and visible height; their difference is the maximum scrollTop. |
event.deltaX, event.deltaY, event.deltaMode |
Wheel movement and its unit (pixels, lines or pages). |
event.ctrlKey |
true for pinch-zoom gestures on many trackpads. |
Usage notes
onScrolldoes not bubble. Since React 17, a scroll on a child does not callonScrollon its parents, matching the browser. Put the handler on the element that scrolls.- Page scrolling: to react to the window scrolling, add a listener to
windowin an effect (and remove it in cleanup);onScrollon<body>or a wrapper does not see it. onWheelis passive.event.preventDefault()does nothing and the browser warns. To cancel a wheel scroll, attach a native listener with{ passive: false }from an effect.- Performance: scroll events fire many times per frame. Keep handlers cheap, store the value in state only when the UI really depends on it, and use
requestAnimationFrame, throttling orIntersectionObserverfor heavier work. - Prefer CSS for sticky headers, snap points and scroll-driven animations, and
IntersectionObserverfor "has this appeared" checks. - Restoring position: write to
ref.current.scrollTopin an effect (orscrollTo) rather than through state. - Long lists: use virtualization instead of reacting to every scroll yourself.