React use debounce with setState

前端 未结 1 2026
南方客
南方客 2021-01-14 14:23

Background

Assume we all know about the debounce function from lodash.

If a user quickly input 1,12,

相关标签:
1条回答
  • 2021-01-14 14:51

    Try this (using useCallback):

    import React, { useState, useCallback } from "react";
    import "./styles.css";
    import { debounce } from "lodash";
    
    const request = debounce(value => {
      alert(`request: ${value}`);
    }, 1000);
    
    export default function App() {
      const [input, setInput] = useState("");
    
      const debouceRequest = useCallback(value => request(value), []);
    
      const onChange = e => {
        debouceRequest(e.target.value);
        setInput(e.target.value); // Remove this line will lead to normal denounce
      };
    
      return (
        <div className="App">
          <input onChange={onChange} />
        </div>
      );
    }
    

    0 讨论(0)
提交回复
热议问题