useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useThrottle

utility

Installation

npx usehooks-cli@latest add use-throttle

Description

A React hook for throttling values to limit the frequency of updates. Unlike debouncing, throttling ensures updates happen at regular intervals during continuous changes.

Parameters

NameTypeDefaultDescription
valueT-The value to throttle
delaynumber-The minimum time in milliseconds between updates

Examples

Scroll Position Throttling

Throttling scroll events for performance

1const [scrollY, setScrollY] = useState(0); 2const throttledScrollY = useThrottle(scrollY, 100); 3 4useEffect(() => { 5 const handleScroll = () => setScrollY(window.scrollY); 6 7 window.addEventListener('scroll', handleScroll); 8 return () => window.removeEventListener('scroll', handleScroll); 9}, []); 10 11// Use throttled value for expensive operations 12useEffect(() => { 13 updateParallaxElements(throttledScrollY); 14}, [throttledScrollY]);

Mouse Movement Tracking

Throttling mouse movement for smooth animations

1const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); 2const throttledMousePos = useThrottle(mousePos, 16); // ~60fps 3 4useEffect(() => { 5 const handleMouseMove = (e: MouseEvent) => { 6 setMousePos({ x: e.clientX, y: e.clientY }); 7 }; 8 9 document.addEventListener('mousemove', handleMouseMove); 10 return () => document.removeEventListener('mousemove', handleMouseMove); 11}, []); 12 13// Smooth cursor following animation 14return ( 15 <div 16 style={{ 17 transform: `translate(${throttledMousePos.x}px, ${throttledMousePos.y}px)` 18 }} 19 /> 20);

API Rate Limiting

Throttling API calls to respect rate limits

1const [searchQuery, setSearchQuery] = useState(''); 2const throttledQuery = useThrottle(searchQuery, 1000); 3 4useEffect(() => { 5 if (throttledQuery) { 6 // API call happens at most once per second 7 searchAPI(throttledQuery); 8 } 9}, [throttledQuery]); 10 11return ( 12 <input 13 value={searchQuery} 14 onChange={(e) => setSearchQuery(e.target.value)} 15 placeholder="Search (throttled)..." 16 /> 17);

Dependencies

react

Notes

  • Unlike debouncing, throttling ensures regular updates during continuous changes
  • First update happens immediately, subsequent updates are limited by the delay
  • Ideal for scroll events, mouse movements, and other high-frequency events
  • Uses a combination of immediate execution and scheduled updates for optimal performance
  • Properly cleans up timeouts on unmount to prevent memory leaks

Implementation

1"use client"; 2 3import { useState, useEffect, useRef } from "react"; 4 5export function useThrottle<T>(value: T, delay: number): T { 6 const [throttledValue, setThrottledValue] = useState<T>(value); 7 const lastExecuted = useRef<number>(Date.now()); 8 const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null); 9 10 useEffect(() => { 11 const now = Date.now(); 12 const timeSinceLastExecution = now - lastExecuted.current; 13 14 if (timeSinceLastExecution >= delay) { 15 // If enough time has passed, update immediately 16 setThrottledValue(value); 17 lastExecuted.current = now; 18 } else { 19 // Otherwise, schedule an update for the remaining time 20 if (timeoutRef.current) { 21 clearTimeout(timeoutRef.current); 22 } 23 24 timeoutRef.current = setTimeout(() => { 25 setThrottledValue(value); 26 lastExecuted.current = Date.now(); 27 }, delay - timeSinceLastExecution); 28 } 29 30 return () => { 31 if (timeoutRef.current) { 32 clearTimeout(timeoutRef.current); 33 } 34 }; 35 }, [value, delay]); 36 37 return throttledValue; 38} 39 40export default useThrottle; 41