How to implement a debounc search normally
Use debuglog
Example(Without React)
Without re-rendering in vanilla javascript
const searchMembersAction = (val) => {
search(val).then((res) => {
if (res) {
setSearchLoading(false);
setDropdownList(
res?.records?.filter(
(rec) => !savedValues?.map(({ id }) => id).includes(rec.id)
)
);
}
});
};
const searchMembers = debounce(searchMembersAction, 400);
searchMembers();
Example(React)
With a lot of re-rendering
const searchMembersAction = (val) => {
search(val).then((res) => {
if (res) {
setSearchLoading(false);
setDropdownList(
res?.records?.filter(
(rec) => !savedValues?.map(({ id }) => id).includes(rec.id)
)
);
}
});
};
const searchMembers = React.useCallback(debounce(action, 400), []);
searchMembers();
Why use React.useCallback?
React re-renders a lot of times, and it leads to creation of different instances of a debounce function
To prevent this new inscance creation on a function, we preserve the reallocation of function using React.useCallback