Author avatar

Manujith Pallewatte

Optimizing Data Fetching in React

Manujith Pallewatte

  • Jun 5, 2020
  • 15 Min read
  • 35,020 Views
  • Jun 5, 2020
  • 15 Min read
  • 35,020 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

Data fetching is a core requirement of almost every real-world React app. Sometimes we are required to interact with APIs that are being called in rapid succession from our web app. An auto-complete search is one example. If these instances are not carefully planned, we could easily end up degrading the performance of the app as well as the API. In this guide, we explore several techniques to optimize data fetch requests and the effect of them.

To demonstrate the ideas discussed in this guide, we will use a simple auto-complete search. Auto-complete is a function expected in any modern app, yet it is often a poorly engineered feature due to its simplicity. Most of the time, developers put thought into providing the best visual output of the component, but the actual issues of data fetching are lost.

The Auto-Complete Search

First, initialize a React-Redux project with one search action added, which will be used to retrieve the search results for the keywords. To keep the guide focus intact, only certain components of the app will be discussed here. But you can find the complete source code at this Github Repo. To provide the auto-complete UI, you can install the react-autocomplete library from npm. With all the components added and initialized, App.js will look as follows.

1import React, { useState } from 'react';
2import './App.css';
3import { Provider, useSelector, useDispatch } from 'react-redux'
4import store from './store';
5import Autocomplete from 'react-autocomplete';
6import { search } from './actions';
7
8function SearchComponent(){
9    const [query, setQuery] = useState("");
10    const hits = useSelector(state => state.hits);
11    const results = useSelector(state => state.searchResults);
12
13    const dispatch = useDispatch();
14
15    const onSearch = (query) => {
16        setQuery(query);
17        dispatch(search(query));
18    }
19
20    return (
21        <div>
22            <div>API hits: {hits}</div>
23            <Autocomplete
24                getItemValue={(item) => item}
25                items={results}
26                renderItem={(item, isHighlighted) =>
27                    <div style={{ background: isHighlighted ? 'lightgray' : 'white' }}>
28                        {item}
29                    </div>
30                }
31                value={query}
32                onChange={(e) => onSearch(e.target.value)}
33            />
34        </div>
35    )
36}
37
38function App() {
39    return (
40        <Provider store={store}>
41            <div className="App">
42                <h2>Auto-complete Search</h2>
43                <SearchComponent />
44            </div>
45        </Provider>
46    )
47}
48
49export default App;
jsx

Note that you access two variables from the Redux store.
1. searchResults: matching strings for a given query
2. hits: number of times the API is called

hits will be used to demonstrate the importance of considering the query optimizations and the effect of each optimization technique. Before you run the above code, take a look at mockapi.js, where a search function is created to mimic the actions of a search API.

1import mockData from './mockdata.json';
2
3var hits = 0;
4
5const sleep = (milliseconds) => {
6    return new Promise(resolve => setTimeout(resolve, milliseconds))
7}
8
9export async function searchAPI(query){
10    await sleep(50);
11    return {
12        data: {
13            results: mockData.filter(item => item.toLowerCase().includes(query)).slice(0, 5),
14            hits: ++hits
15        }
16    }
17}
js

A simple counter is used to track the number of API hits to this mock search API. Now run the complete code and try typing in few keywords, such as samsung and samsung galaxy. You will notice that while you are typing, with each keystroke the number of hits increases, meaning that your API has been called that many times. Most of the intermediate API calls were unnecessary. So today's goal is to reduce the number of hits without degrading the user experience.

Debouncing

Debouncing is a form of action delay where a defined period is observed after the last call to a function is fired. This means that if a user is typing a word, the app buffers all search calls until the user stops typing, and then waits for another period to see if the user starts typing again. If not, then it fires the last received function call. Considering the above autocomplete function, for instance, this means that for the search query samsung s10 it would fire only one search action with the query parameter as samsung s10. Earlier, it would have dispatched ten actions, one for every keystroke of the user.

Apart from saving the bandwidth of your API, debouncing also prevents excessive re-rendering of React components. For example, if you are showing the results of the query live while typing, for each response received, the result component would be re-rendered.

There are several ways to implement debouncing in React. You could either write your own debounce implementation, or use a library that would provide the functionality. Some widely used libraries are:

In this guide, you will use lodash. If you would rather implement the functionality yourself, this article provides excellent examples. You can install lodash with npm install --save lodash.

The following example shows how the lodash debounce function is used to limit the action calls.

1// actions.js 
2
3import * as mockAPI from './mockapi';
4import debounce from 'lodash/debounce';
5
6// These are our action types
7export const SEARCH_REQUEST = "SEARCH_REQUEST"
8export const SEARCH_SUCCESS = "SEARCH_SUCCESS"
9export const SEARCH_ERROR = "SEARCH_ERROR"
10
11
12// Now we define actions
13export function searchRequest(){
14    return {
15        type: SEARCH_REQUEST
16    }
17}
18
19export function searchSuccess(payload){
20    return {
21        type: SEARCH_SUCCESS,
22        payload
23    }
24}
25
26export function searchError(error){
27    return {
28        type: SEARCH_ERROR,
29        error
30    }
31}
32
33export function search(query) {
34    return async function (dispatch) {
35        dispatch(searchRequest());
36        try{
37            const response = await mockAPI.searchAPI(query);
38            dispatch(searchSuccess(response.data));
39        }catch(error){
40            dispatch(searchError(error));
41        }
42    }
43}
44
45// debouncing the searchAPI method with wait time of 800 miliseconds
46// note that we have leading=true, means that initial function call will be fired
47// before starting the wait time
48// withut it return value is initial null, which will break the search code
49const debouncedSearchAPI = debounce(async (query) => {
50    return await mockAPI.searchAPI(query)
51}, 800, { leading: true });
52
53export function debouncedSearch(query) {
54    return async function (dispatch) {
55        dispatch(searchRequest());
56        try{
57            const response = await debouncedSearchAPI(query);
58            dispatch(searchSuccess(response.data));
59        }catch(error){
60            dispatch(searchError(error));
61        }
62    }
63}
javascript

SearchPage needs to be modified to use the debounced search in place of the regular search as well.

1// SearchPage.js
2// ....
3
4    const onSearch = (query) => {
5            setQuery(query);
6            dispatch(debouncedSearch(query));
7    }
8
9// ...
jsx

Now, try running the same set of queries as above and observe the change in the number of API hits. You can experiment with the buffer time in the debounce function to get a better idea of the effect of debouncing. While this prevents the problem of rapid API call execution, now the user experience seems to be degraded. An ideal auto-complete should provide suggestions while the user is typing, whereas the current implementation would only provide suggestions after the user has stopped typing. To correct this, you could use the next optimization technique: throttling.

Throttling

Throttling provides optimization by limiting the number of actions of the same function being called in a given interval of time. For example, you could determine that the search action should only be fired every 100 milliseconds. This way, regardless of whether the user is still typing or not, the search action will be dispatched once every 100 milliseconds, improving the user experience.

You can use the same library you used for debouncing for throttling as well. The following example has modified the previous code to implement throttling.

1// actions.js
2
3import * as mockAPI from './mockapi';
4import debounce from 'lodash/debounce';
5import throttle from 'lodash/throttle';
6
7// These are our action types
8export const SEARCH_REQUEST = "SEARCH_REQUEST"
9export const SEARCH_SUCCESS = "SEARCH_SUCCESS"
10export const SEARCH_ERROR = "SEARCH_ERROR"
11
12
13// Now we define actions
14export function searchRequest(){
15    return {
16        type: SEARCH_REQUEST
17    }
18}
19
20export function searchSuccess(payload){
21    return {
22        type: SEARCH_SUCCESS,
23        payload
24    }
25}
26
27export function searchError(error){
28    return {
29        type: SEARCH_ERROR,
30        error
31    }
32}
33
34export function search(query) {
35    return async function (dispatch) {
36        dispatch(searchRequest());
37        try{
38            const response = await mockAPI.searchAPI(query);
39            dispatch(searchSuccess(response.data));
40        }catch(error){
41            dispatch(searchError(error));
42        }
43    }
44}
45
46const debouncedSearchAPI = debounce(async (query) => {
47    return await mockAPI.searchAPI(query)
48}, 800, { leading: true });
49
50export function debouncedSearch(query) {
51    return async function (dispatch) {
52        dispatch(searchRequest());
53        try{
54            const response = await debouncedSearchAPI(query);
55            dispatch(searchSuccess(response.data));
56        }catch(error){
57            dispatch(searchError(error));
58        }
59    }
60}
61
62const throttledSearchAPI = throttle(async (query) => {
63    return await mockAPI.searchAPI(query)
64}, 300, { leading: true });
65
66export function throttledSearch(query) {
67    return async function (dispatch) {
68        dispatch(searchRequest());
69        try{
70            const response = await throttledSearchAPI(query);
71            dispatch(searchSuccess(response.data));
72        }catch(error){
73            dispatch(searchError(error));
74        }
75    }
76}
javascript
1// SearchPage.js
2// ....
3
4    const onSearch = (query) => {
5            setQuery(query);
6            dispatch(throttledSearch(query));
7    }
8
9// ...
jsx

Make the changes and observe how the search experience is now changed with throttling when compared to debouncing alone. Note that each technique has its use cases. So it's the developer's task to select the correct tool.

Request-Response Matching

By using either of the above techniques, you can significantly improve the data-fetching aspects of your web apps. Yet, when it comes to a real-world application, there are unforeseen complications, such as network delays and unpredictable processing times in database servers. As a result, your API might not return results in the same order that you sent them.

Assume that in the above scenario, two consecutive search queries are dispatched to a real API as follows.
1. /search?q=samsung galaxy
2. /search?q=samsung galaxy watch

This would yield two responses. Response 1:

1{
2    "data": {
3        "results": ["samsung galaxy", "samsung galaxy s10", ...]
4        "hits": <hit number>
5    }
6}

Response 2:

1{
2    "data": {
3        "results": ["samsung galaxy watch", "samsung galaxy watch 2", ...]
4        "hits": <hit number>
5    }
6}

It is apparent that the user's last query here is samsung galaxy watch. So, the auto-complete should ideally show results that include samsung galaxy watch rather than just samsung galaxy. But due to network delays, Response 1 may arrive after Response 2. This means the auto-complete is showing an incorrect result set to the user.

To prevent such occurrences, you can use a request-response mapping technique. This generally involves making changes to your API as well as to your web app. For the above scenario, you could resolve by changing the API to return the search query along with the search results. Then the response can be validated by matching the returned query with the stored query.

1// mockapi.js
2
3export async function searchAPI(query){
4    await sleep(50);
5    return {
6        data: {
7            results: mockData.filter(item => item.toLowerCase().includes(query)).slice(0, 5),
8            hits: ++hits,
9            query: query
10        }
11    }
12}
js

Reducer is updated to store the current user query before dispatching the API call. The searchRequest action reducer facilitates this. And on receiving the search results, the query returned from the API is compared to determine if the results should be updated or not.

1// reducers.js
2
3import { SEARCH_REQUEST, SEARCH_SUCCESS } from './actions';
4
5const initialState = {
6    searchResults: [],
7    hits: 0,
8    currentQuery: ""
9}
10
11export default function searchReducer(state, action) {
12    if (typeof state === 'undefined') {
13        return initialState
14    }
15
16    switch(action.type){
17        case SEARCH_REQUEST:
18            state.currentQuery = action.payload;
19            break;
20
21        case SEARCH_SUCCESS:
22            if(state.currentQuery === action.payload.query){
23                state.searchResults = action.payload.results;
24                state.hits = action.payload.hits;
25            }
26            break;
27    }
28
29    return state
30}
js
1// actions.js
2
3// ...
4export function search(query) {
5    return async function (dispatch) {
6        dispatch(searchRequest(query));
7        try{
8            const response = await mockAPI.searchAPI(query);
9            dispatch(searchSuccess(response.data));
10        }catch(error){
11            dispatch(searchError(error));
12        }
13    }
14}
15//...
js

Note that there is no one correct solution for integrating such mappings. The solution will depend on your API architecture and the web app. But as a practice, tagging a uniquely generated ID with a request can be used.

Conclusion

In this guide, we explored a simple use case of an auto-complete search and its effect on API load if optimization is not done in data fetching. We used debouncing and throttling as two techniques to optimize it and observed how each would affect the API load as well as the user experience. Finally, we improved the solution further by request-response mapping to consider practical errors that can occur in a real-world application.