Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strange behaviour with React useState + debounce #61

Closed
pxtnpxtn opened this issue Oct 18, 2022 · 5 comments
Closed

Strange behaviour with React useState + debounce #61

pxtnpxtn opened this issue Oct 18, 2022 · 5 comments

Comments

@pxtnpxtn
Copy link

Hello!

I am trying to get debounce to work in my project. In the input's onChange, if it also contains a setState, then the debounce function stops working and instead prints out each key stroke individually. I'm wanting the setState to be there, because the value will come from localStorage, and the useState's value is used elsewhere in my app.

https://codesandbox.io/s/adoring-nova-exxfwf?file=/src/App.js

Any explanation on what is happening and how I can work around it would be much appreciated!

Thanks.

@niksy
Copy link
Owner

niksy commented Oct 19, 2022

@pxtnpxtn is this similar to #47?

@Hades30
Copy link

Hades30 commented Oct 19, 2022

wrapping the debounce function with useCallback fixed the problem , this happens because whenever a state changes , you are creating multiple debounce functions which is basically creating multiple callbacks with a delay.

@pxtnpxtn
Copy link
Author

pxtnpxtn commented Oct 19, 2022

wrapping the debounce function with useCallback fixed the problem , this happens because whenever a state changes , you are creating multiple debounce functions which is basically creating multiple callbacks with a delay.

That does make a lot of sense, thank you @Hades30. I wrapped it in a useCallback though and not doesn't seem to be logging anything at all. What am I missing?

const searchAddress = useCallback(() => {
    debounce(1000, (text) => {
      console.log("text==>", text);
      // Some API call
    });
  }, []);

https://codesandbox.io/s/adoring-nova-exxfwf?file=/src/App.js

@Hades30
Copy link

Hades30 commented Oct 20, 2022

@pxtnpxtn
Copy link
Author

pxtnpxtn commented Oct 20, 2022

Thank you kindly @Hades30. Really appreciate your time.

For anyone in the future facing this issue:

const searchAddress = useCallback(
    debounce(1000, (text) => {
      console.log("text==>", text);
      // Some API call
    }),
    []
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants