Implementing “Lodash” in a React Project

The other day I was working on a little post-Flatiron School project to strengthen my React/Redux skills. The project is a YouTube search/player app that allows the user to search YouTube videos and play videos from the results.

The app has a search bar input at the top of the screen that has an onChange event that sets the state to the new search term. When the new state is set, the YouTube API is hit with the search term, and results are returned and shown on the screen.

I realized that the app started to lag somewhat because each keystroke was causing an update in state and a new search through the YouTube API. That amount of API calls is unnecessary, but it is how I wanted the app to work. I wanted it to make these calls, but not after every keystroke, I wanted it to be made every few seconds instead. But that seemed hard…

Then I came across this JavaScript library called “Lodash” or just _. “Lodash” is a Javascript library that makes it easier to work with arrays, numbers, objects, and strings in Javascript.

So, Lodash has extensive documentation that will help you accomplish many tasks. The _.debounce function was most helpful for my situation.

_.debounce(func, [wait=0], [options={}])

The above debounce function will call a function after waiting a certain amount of time. So, in my app, I decided to implement this function in a way that the onChange is calling the debounce function. So each time a keystroke is made in the search bar, the API is being called after waiting a certain amount of time. If this function is called multiple times, it will start the time with the first call and in my case hit the API after 300 ms.

const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);

The above is the code that I used in my app. I chose 300, so that a request to the API would only be made every 300 ms when the search bar is detecting changes.

After adding this code, my app has been running cleaner and without the lag that I noticed before.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.