乐闻世界logo
搜索文章和话题

How to use throttle or debounce with React Hook?

1个答案

1

Debouncing

Implementing debouncing in React typically involves using the useEffect hook in combination with an external debouncing function. The purpose of debouncing is to ensure that only the last event is processed after a specified delay when events are triggered continuously. This is particularly useful in scenarios such as real-time search in input fields.

Here is an example using the debounce function from the lodash library:

jsx
import React, { useState, useEffect } from 'react'; import { debounce } from 'lodash'; function SearchComponent() { const [inputValue, setInputValue] = useState(''); const debouncedSave = debounce((nextValue) => { // Actual business logic, such as calling an API console.log('Saving data', nextValue); }, 1000); // Delay of 1 second useEffect(() => { debouncedSave(inputValue); // Cleanup function to cancel the debounced action when the component unmounts return () => debouncedSave.cancel(); }, [inputValue, debouncedSave]); return ( <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="Type to search..." /> ); }

In this example, we use useState to store the input value and useEffect to listen for changes to this value. When the input value changes, the useEffect hook calls the debouncedSave function, but because this function is debounced, it only executes after continuous operations stop.

Throttling

Throttling is similar to debouncing but ensures that the event handler is executed at most once within a specified time period. This is particularly useful for handling high-frequency events like scroll events, as these events may trigger multiple times in a short period, and we only need to execute certain code sparsely.

Here is an example using the throttle function from the lodash library:

jsx
import React, { useState, useEffect } from 'react'; import { throttle } from 'lodash'; function ScrollComponent() { const [position, setPosition] = useState(window.scrollY); const throttledHandleScroll = throttle(() => { setPosition(window.scrollY); console.log('Scroll position', window.scrollY); }, 1000); // Triggered at most once per second useEffect(() => { window.addEventListener('scroll', throttledHandleScroll); return () => { window.removeEventListener('scroll', throttledHandleScroll); throttledHandleScroll.cancel(); } }, [throttledHandleScroll]); return ( <div> <p>Current scroll position: {position}</p> </div> ); }

In this example, we create a throttled function throttledHandleScroll that executes when the user scrolls the page, but due to throttling, it only executes once per second regardless of how frequently the user scrolls. We use the useEffect hook to add and clean up event listeners.

2024年6月29日 12:07 回复

你的答案