Potential React Bloatiness

React can become bloaty. Or for that matter, every project that uses javascript (e.g. npm/nodejs projects).

I recently wanted to add a search feature to a website. The natural thing is to want to debounce the user’s input before passing the search string to the server. So, obviously, one doesn’t have to implement a debounce function – you can take it from lodash. But then the question arises – how would one integrate that debouncing into a react project? Or worse yet, an asp.net core + react + redux + typescript project?

Well, here’s a nice little SO thread:
https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js

It’s top answer has almost 900 upvotes, it spans tons of text, with a yearly history. It also suggests using three different code sources to get the thing to work. That’s bananas!

So how did I go about solving this?

Actually, a far less popular SO thread also caught my eye: https://stackoverflow.com/questions/43709356/debounce-textarea-input-with-react-redux

This was much much better! It’s a classic SO answer – no history lesson needed, no need to take a ton of dependencies. It even has an inline working code sample – superb!

The solution is actually very simple – the textarea’s callback should do two things – update the local text, and invoke the debounce function. Not a single dependecy added. Well, almost, since the debounce function is taken from lodash. But I have to admit – taking a lodash dependecy when just single function is required? Why not just take a debounce function from somewhere?

Well, that’s what I did. I took one from here, and adjusted it to compile: https://gist.github.com/ca0v/73a31f57b397606c9813472f7493a940

My final code looked like this:

export const debounce = <T extends (...args: any[]) => any>(
    callback: T,
    waitFor: number
) => {
    let theTimeout: any = 0;
    return (...args: Parameters<T>): ReturnType<T> => {
        let result: any;
        clearTimeout(theTimeout);
        theTimeout = setTimeout(() => {
            result = callback(...args);
        }, waitFor);
        return result;
    };
};

To summarize, imo, there’s a big difference between taking a single function to taking four dependencies. It’s one of those sad cases where SO isn’t accurate, or optimized in any way. Something to keep in mind when browsing SO. šŸ™‚

Leave a Comment