0 day streak
javascript / expert
Snippet

Imperative Scroll Synchronization with Refs

When building complex UIs like side-by-side code editors, you often need to imperatively sync the scroll position of two elements using refs to bypass the overhead of state-driven rendering for every pixel.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
const useScrollSync = () => {
const master = React.useRef(null);
const slave = React.useRef(null);
const handleScroll = (e) => {
if (e.target === master.current) {
slave.current.scrollTop = master.current.scrollTop;
}
};
return { master, slave, handleScroll };
};
react
Breakdown
1
const master = React.useRef(null);
Creates a reference to the primary scrollable DOM element.
2
slave.current.scrollTop = master.current.scrollTop;
Directly manipulates the DOM property of the second element to match the first.