Server-side search in React-table

Karthik Raja
3 min readApr 1, 2022
Photo by Mike

This is the second part of React-table series where we’ll see how to implement serve side search in react-table. I’ll be using the same code base that I used in server side pagination as most of the logic will be similar. So, I recommend you to check the first part before proceeding.

What and why of server-side search

Imagine you have 1000 rows of data that you are fetching from backend and displaying it in your app (BTW, you shouldn’t do it actually). On top of that you have a search field that searches for a particular data within the available 1000 rows for every keystroke. This scenario has 3 problems, that we’ll address

  1. Fetching huge amount of data — This is can be handled using server-side pagination
  2. Handling search in client side with large amount of data — This will put unnecessary load in frontend and make the app slower. Also you might miss the data you are looking for if it’s not in that particular 1000 rows of data. This is where server-side search comes to action. It takes the heavy lifting of searching the entire data to the backend. We’ll see how it’s done.
  3. I’ll explain the third issue after we’ve implemented server-side search.

The logic for server-side search is same as server-side pagination: Just limit the data supplied to react-table.

Let’s get started

Pre-requisite

An API that supports querying and a helper method that calls the API.

Setting up

First, we’ll add a controlled input field where we can type the search term

Next, we’ll have to call the API whenever the user types something in the input field and supply back the data received to react-table. This is same as what we did for pagination. And that’s pretty much it.

With a little bit of fine tuning the flow and refactoring, we get a fully functional server-side search/pagination capable react-table:

We have successfully implemented the server-side search in our React app. But, there’s a new problem now. The search API will be called every time the search value changes, i.e for every keystroke. This will cause problem in backend as every hit to the database is a costly operation. This is the third issue I mentioned earlier. So, how to solve this?

By debouncing/throttling the API requests

Debouncing is a method by which we can delay the execution of a function by some time

If you want to learn about debouncing in React, check the following article. I’ll just use the custom hook given in the article.

The final code

Please note that this debouncing implementation is my own one. There are other much stable implementations available in the form of custom hooks and npm packages. So, you can choose whichever you want.

You can find the entire code here.

Thanks

--

--