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

How can I perform a debounce in React ?

3个答案

1
2
3

In React, implementing a debounce function typically involves using a specific function within a component that delays the execution of actual processing logic until a period of inactivity has passed. This reduces the number of calls to event handling functions, such as continuous input in a text field, thereby improving performance.

  1. Create the debounce function: Create a debounce function that accepts a function func to be delayed and a wait time wait.
javascript
const debounce = (func, wait) => { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; };
  1. Use the debounce function in a React component: Implement debounce functionality by combining the useEffect hook with the debounce function.

Suppose we have a search input field, and we want to trigger the search after a period of inactivity, avoiding searches on every keystroke:

javascript
import React, { useState, useEffect } from 'react'; const SearchComponent = () => { const [inputValue, setInputValue] = useState(''); // Define the debounce function const debounceSearch = debounce((searchValue) => { console.log(`Search: ${searchValue}`); // Execute search logic here, e.g., API call }, 500); useEffect(() => { if (inputValue) { debounceSearch(inputValue); } }, [inputValue]); return ( <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="Enter keywords to search" /> ); }; export default SearchComponent;

In the above example, we set the inputValue in the onChange event of the input field, and use inputValue as a dependency in useEffect, indicating that the effect callback executes when inputValue changes. Within the effect callback, we call debounceSearch, which delays the execution of the search logic until 500 milliseconds after the user stops typing.

This way, regardless of how fast the user types, the actual search logic only executes after a period of inactivity, significantly reducing unnecessary processing and API calls.

2024年6月29日 12:07 回复

Here is a simple approach to implementing debounce using React hooks.

Step 1: Define a state to maintain the search text.

javascript
const [searchTerm, setSearchTerm] = useState('')

Step 2: Use useEffect to capture changes to searchTerm.

javascript
useEffect(() => { const delayDebounceFn = setTimeout(() => { if (searchTerm) { // Implement your logic here } }, 400) return () => clearTimeout(delayDebounceFn) }, [searchTerm])

Step 3: Write a function to handle input changes.

javascript
function handleInputChange(value) { if (value) { setSearchTerm(value) } }
2024年6月29日 12:07 回复

Uncontrolled Components

You can use the event.persist() method.

Here is an example of using Underscore.js's _.debounce():

javascript
var SearchBox = React.createClass({ componentWillMount: function () { this.delayedCallback = _.debounce(function (event) { // `event.target` is accessible now }, 1000); }, onChange: function (event) { event.persist(); this.delayedCallback(event); }, render: function () { return ( <input type="search" onChange={this.onChange} /> ); } });

See this JSFiddle.


Controlled Components

The above example shows an uncontrolled component. I always use controlled elements, so here is another example without using event.persist() as a workaround.

JSFiddle is also available. Example without Underscore.js

javascript
var SearchBox = React.createClass({ getInitialState: function () { return { query: this.props.query }; }, componentWillMount: function () { this.handleSearchDebounced = _.debounce(function () { this.props.handleSearch.apply(this, [this.state.query]); }, 500); }, onChange: function (event) { this.setState({query: event.target.value}); this.handleSearchDebounced(); }, render: function () { return ( <input type="search" value={this.state.query} onChange={this.onChange} /> ); } }); var Search = React.createClass({ getInitialState: function () { return { result: this.props.query }; }, handleSearch: function (query) { this.setState({result: query}); }, render: function () { return ( <div id="search"> <SearchBox query={this.state.result} handleSearch={this.handleSearch} /> <p>You searched for: <strong>{this.state.result}</strong></p> </div> ); } }); React.render(<Search query="Initial query" />, document.body);
2024年6月29日 12:07 回复

你的答案