MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Throttled Scroll Progress with Explanation

ReactJS Hard Performance & Patterns 19 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around scroll, progress, update. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Update scroll progress smoothly without setting state on every scroll event.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use requestAnimationFrame to throttle state updates.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
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> ); }

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next