i follow this link to handle input:
const handleSearch = useMemo(() => {
_.debounce(text => {
console.log(text);
});
}, []);
const handleOnSearch = useCallback(
text => {
handleSearch(text);
},
[handleSearch],
);
but i get error: handleSearch is not a function
(this error only trigger when i enter text into the input)
But if i use this code, everything ok:
const handleSearch = useRef(
_.debounce(over => {
console.log(over);
}, 1000),
);
const handleOnSearch = useCallback(text => {
setTextSearch(text);
handleSearch.current(text);
}, []);
Can someone explain to me please?
2
Answers
You are not returning the value from
_.debounce
sohandleSearch
gets undefineduseMemo
returns the value from the callback, passed to it as argument. And your callback does not return anything.You can do it like this as well, the same as using
useRef
:But here
_.debounce
will execute on each renderuseMemo is expecting a callback and it will return the callback result.
its purpose is to cache the result so the callback doesn’t need to be re-run every time the component is rendered.
So since the callback sent to useMemo doesn’t return a value,
handleSearch
is undefined. this is how you fix it:however – I don’t see much purpose is the way you are combining useMemo and useCallback, since the handleSearch never changes, and handOnSearch only calls handleSearch.
Therefore, you can reduce them to a single useMemo (you can use useCallback but I think this is slightly more readable):
and then whenever you use
handleOnSearch
just usehandleSearch