๐Ÿงช Challenges

Throttle Scroll

Challenge 8 - Medium

Description

Create a component that executes a throttled action when a scroll event occurs. This technique optimizes performance by limiting how often the scroll handler is executed.

Objective

Implement the throttle logic to control the frequency of the scroll event's effect.

1. Example

Scroll down to see the throttled scroll action in action. Check the console for the throttled output.

Throttle div

2. Implementation

Interface

The component renders a div that demonstrates throttling of scroll events, optimizing performance by limiting the frequency of the scroll handler's execution. It uses state to track the last execution time of the event handler and triggers the function only if the defined interval (THROTTLE_TIME) has passed. The component attaches and cleans up the scroll event listener dynamically usinguseEffecthook amd it's a practical example of handling high-frequency events in React.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 const THROTTLE_TIME = 1000; const ThrottleScroll: React.FC<ThrottleScrollPropType> = () => { const [lastCall, setLastCall] = useState(0); const handleScroll = () => { const now = Date.now(); if(now - lastCall > THROTTLE_TIME) { setLastCall(now); console.log(`THROTTLED SCROLL`); } }; useEffect(() => { window.addEventListener('scroll', handleScroll); return ( () => { window.removeEventListener('scroll', handleScroll); }); }, [handleScroll]); return ( <div> Throttle div </div> ); }; export default ThrottleScroll;
๐Ÿ›๏ธ ๐Ÿงฎ ๐Ÿ“ โš›๏ธ ๐Ÿงช ๐Ÿ