React use debounce with setState

巧了我就是萌 提交于 2020-04-07 08:12:28

问题


Background

Assume we all know about the debounce function from lodash.

If a user quickly input 1,12,123,1234, it allows us to proceed an alert only once, with 1234, after a certain delay time.

This is quite used to reduce request amount, for optimization.


Description

For a normal input field, we can use that kind of debounce and it works.

Problem: Once we add a setState inside the same callback with debounce, the debounce won't work as normal.

Does anyone know the reason?

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

export default function App() {
  const [input, setInput] = useState("");

  const debouceRequest = debounce(value => {
    alert(`request: ${value}`);
  }, 1000);
  const onChange = e => {
    setInput(e.target.value); // Remove this line will lead to normal debounce
    debouceRequest(e.target.value);
  };

  return (
    <div className="App">
      <input onChange={onChange} />
    </div>
  );
}


回答1:


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>
  );
}



来源:https://stackoverflow.com/questions/60789246/react-use-debounce-with-setstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!