Throttled Scroll Progress
ReactJS
Hard
7 views
Problem Description
Update scroll progress smoothly without setting state on every scroll event.
Output Format
Render a React component.
Constraints
Use requestAnimationFrame to throttle state updates.
Official Solution
import React, { useRef, useState } from 'react';
export default function App() {
const [pct, setPct] = useState(0);
const raf = useRef(0);
function onScroll(e) {
const el = e.currentTarget;
const max = el.scrollHeight - el.clientHeight;
const nextPct = max <= 0 ? 0 : Math.round((el.scrollTop / max) * 100);
if (raf.current) cancelAnimationFrame(raf.current);
raf.current = requestAnimationFrame(() => setPct(nextPct));
}
const blocks = Array.from({ length: 40 }, (_, i) => i + 1);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode reading</h2>
<div style={{ height: 10, borderRadius: 999, background: '#eee', overflow: 'hidden' }}>
<div style={{ height: '100%', width: pct + '%', background: '#0b5' }} />
</div>
<div style={{ marginTop: 8, color: '#555' }}>Progress: {pct}%</div>
<div onScroll={onScroll} style={{ marginTop: 10, height: 240, overflow: 'auto', border: '1px solid #eee', borderRadius: 14, padding: 12 }}>
{blocks.map((n) => (
<div key={n} style={{ padding: '10px 0', borderBottom: '1px solid #f3f4f6' }}>
Block {n} on meetcode
</div>
))}
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!