About the actual implementation, this wouldn’t produce a great DX mainly because we need to pass a dependency list even if we want to runt it "always", so deps ideally should be optional as it is for useEffect, but then we have the problem that you put delay as the last argument, and that one is required. Ideally the argument order should change like this:
import{useDebounce}from"./useDebounce";// Outside your component:constuse1SecondDebounce=useDebounce(1_000);// Inside your component:use1SecondDebounce(changeSearchState,[search]);
Still, my recommendation would be to use a library for this, like the pretty good use-debounce.
And you could even make it into a curried function and keep it pretty similar to a regular hook:
Not useful in this case, yes we can suppress TS warning but It will not be a good idea.
React Hook useEffect cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.
React Hook useDebouncedEffect cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.
The linter doesn't know how are you using your code so it gives you those warnings, if you use it as I said (first call of the curried version outside the component, second inside) it works exactly the same as a regular hook. Linters are there to help, but they aren't silver bullets, you have to understand the reason for the warnings and errors you get.
Using TypeScript, you should avoid
anyas much as possible, so a fixed version would look more like this:About the actual implementation, this wouldn’t produce a great DX mainly because we need to pass a dependency list even if we want to runt it "always", so
depsideally should be optional as it is foruseEffect, but then we have the problem that you putdelayas the last argument, and that one is required. Ideally the argument order should change like this:And you could even make it into a curried function and keep it pretty similar to a regular hook:
And then you use it like this:
Still, my recommendation would be to use a library for this, like the pretty good use-debounce.
Cheers!
Not useful in this case, yes we can suppress TS warning but It will not be a good idea.
The linter doesn't know how are you using your code so it gives you those warnings, if you use it as I said (first call of the curried version outside the component, second inside) it works exactly the same as a regular hook. Linters are there to help, but they aren't silver bullets, you have to understand the reason for the warnings and errors you get.
Didn't tried the
use-debouncebut theloadsh'sDebounce was having some state persistence issue.Your comment is super helpful, thanks man 🤘