Skip to content

Instantly share code, notes, and snippets.

@hungdev
Created April 16, 2021 06:51
Show Gist options
  • Select an option

  • Save hungdev/4979cd01b6811c484a2ef24f68d89827 to your computer and use it in GitHub Desktop.

Select an option

Save hungdev/4979cd01b6811c484a2ef24f68d89827 to your computer and use it in GitHub Desktop.
debound hook
import React, { useState, useCallback } from "react";
import "./styles.css";
import { debounce } from "lodash";


export default function App() {
  const [userQuery, setUserQuery] = useState("");
  const sendQuery = query => console.log(`Querying for ${query}`);
  const delayedQuery = useCallback(debounce(q => sendQuery(q), 500), []);
  const onChange = e => {
    setUserQuery(e.target.value);
    delayedQuery(e.target.value);
  };

  return (
    <div className="App">
      <h2>Start editing to see some magic happen!</h2>
      <input value={userQuery} onChange={onChange} />
    </div>
  );
}

https://codesandbox.io/s/debounce-hook-zgmpn?file=/src/App.js:0-600

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment