So as i understand the difference between the two is that useCallback is used if a function or object or array is returned while useMemo when a primitive is returned. But i was looking up debouncing (this is the article: https://dmitripavlutin.com/react-throttle-debounce/ and it said useMemo would be a better solution. With useCallback
import { useState, useCallback } from 'react';
import debounce from 'lodash.debounce';
export function FilterList({ names }) {
const [query, setQuery] = useState("");
let filteredNames = names;
if (query !== "") {
filteredNames = names.filter((name) => {
return name.toLowerCase().includes(query.toLowerCase());
});
}
const changeHandler = event => {
setQuery(event.target.value);
};
const debouncedChangeHandler = useCallback(
debounce(changeHandler, 300)
, []);
return (
<div>
<input
onChange={debouncedChangeHandler}
type="text"
placeholder="Type a query..."
/>
{filteredNames.map(name => <div key={name}>{name}</div>)}
</div>
);
}
With useMemo
import { useState, useMemo } from 'react';
import debounce from 'lodash.debounce';
export function FilterList({ names }) {
const [query, setQuery] = useState("");
let filteredNames = names;
if (query !== "") {
filteredNames = names.filter((name) => {
return name.toLowerCase().includes(query.toLowerCase());
});
}
const changeHandler = (event) => {
setQuery(event.target.value);
};
const debouncedChangeHandler = useMemo(
() => debounce(changeHandler, 300)
, []);
return (
<div>
<input
onChange={debouncedChangeHandler}
type="text"
placeholder="Type a query..."
/>
{filteredNames.map(name => <div key={name}>{name}</div>)}
</div>
);
}
And i don't understand. Is debounce returning a primitive value? If not how can we use useMemo? Also how is useMemo better than useCallback here?
useCallback
takes a function, and returns that function memoized.useMemo
takes a function that returns a value, runs that function, and memoizes that return value. – Vasectomy