DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Debounce Example

React Functional Component

import React from "react";
import { render } from "react-dom";

const debounce = (func, delay) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func(...args);
    }, delay);
  };
};

const printData = (data) => {
  console.log("data", data);
};

// const getData = debounce((input) => printData(input), 5000);
// OR
const getData = debounce(printData, 5000);

const App = (props) => {
  return (
    <div>
      <h2>Debounce Example List</h2>
      <input type="text" onChange={(event) => getData(event.target.value)} />
    </div>
  );
};

render(<App />, document.getElementById("root"));

Enter fullscreen mode Exit fullscreen mode

React Class Based Components

import React from "react";
import "./EmployeeList.css";

class EmployeesList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      employees: this.props.employees,
      searchTerm: "",
    };
    this.filterMethod = this.debounceSearchResult(
      this.filterMethod.bind(this),
      5000
    );
  }

  debounceSearchResult(func, delay) {
    let timer;
    return function () {
      let context = this;
      let args = arguments;
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(context, args);
      }, delay);
    };
  }

  filterMethod(e) {
    console.log(e);
    this.setState({
      searchTerm: e.toLowerCase(),
    });
  }

  render() {
    return (
      <React.Fragment>
        <div className="controls">
          <label className="format-label">Please Enter employee Name</label>
          <input
            type="text"
            className="filter-input"
            data-testid="filter-input"
            onChange={(e) => this.filterMethod(e.target.value)}
          />
        </div>
        <React.Fragment>
          <div>
            <ul className="employees-list">
              {this.state.employees.map((employee) => {
                if (
                  employee.name.toLowerCase().includes(this.state.searchTerm)
                ) {
                  return (
                    <li key={employee.name} data-testid="employee">
                      {employee.name}
                    </li>
                  );
                }
              })}
            </ul>
          </div>
        </React.Fragment>
      </React.Fragment>
    );
  }
}

export default EmployeesList;

Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)