Medium
When building a music streaming app, you notice user actions (like seeking in a track) are causing too many API calls. How would you optimize the custom hook below to reduce server load while maintaining a smooth user experience?
1function useTrackProgress({ trackId, onTimeUpdate }) {2 const [currentTime, setCurrentTime] = useState(0);3 const [isSeeking, setIsSeeking] = useState(false);4 const audioRef = useRef(null);56 const handleSeek = (newTime) => {7 setIsSeeking(true);8 setCurrentTime(newTime);9 // Missing optimization code here10 audioRef.current.currentTime = newTime;11 onTimeUpdate(newTime);12 setIsSeeking(false);13 };1415 useEffect(() => {16 // Sync with server17 const updateServer = () => {18 if (!isSeeking) {19 fetch('/api/tracks/progress', {20 method: 'POST',21 body: JSON.stringify({22 trackId,23 timestamp: currentTime24 })25 });26 }27 };2829 updateServer();30 }, [currentTime, trackId, isSeeking]);3132 return { currentTime, handleSeek };33}