Search code examples
javascriptreactjsdebouncing

How to clear input value using debounce in reactjs


I'm making search logic. And I'm using debounce also to avoid sending too many API requests. I want to reset input value. But i dont know how to clear input value using debounce. help me.

import { useRef, useState } from "react";
import { debounce } from "lodash";
import "./styles.css";

export default function App() {
  const [text, setText] = useState("");

  const debounceOnChange = debounce((search) => {
    setText(search);
  }, 500);

  const onChangeInput = (event) => {
    const search = event.target.value;
    debounceOnChange(search);
  };

  const inputRef = useRef(null);

  const onClickReset = () => {
    setText("");
    // inputRef?.current?.value = "";
  };

  return (
    <div className="App">
      <input type="text" onChange={onChangeInput} ref={inputRef} />
      <button onClick={onClickReset}>reset</button>
      <br />
      {text}
    </div>
  );
}

This is my codesandbox example. https://codesandbox.io/s/autumn-darkness-qsh9jf?file=/src/App.js

when click reset button, input value should be cleared


Solution

  • I think you don't need to use debounce method

    for your better understanding, I made a code sandbox example for you

    check out this https://codesandbox.io/s/confident-bohr-vlgggj?file=/src/App.js:0-870