InstantSearch / React / V6 / Guides

Improve Performance for React InstantSearch

This version of React InstantSearch has been deprecated in favor of the latest version of React InstantSearch.

Algolia is fast by default. But network speed and bandwidth can vary. This page lists a few best practices you can implement to adapt to your users’ network conditions.

Prepare the connection to Algolia

When sending the first network request to a domain, a security handshake must happen, consisting of several round trips between the client and the Algolia server. If the handshake first happened when the user typed their first keystroke, the speed of that first request would be significantly slower.

Use a preconnect link to carry out the handshake immediately after loading the page but before any user interaction. To do this, add a link tag with your Algolia domain in the head of your page.

1
2
3
4
<link crossorigin href="https://YOUR_APPID-dsn.algolia.net" rel="preconnect" />

<!-- for example: -->
<link crossorigin href="https://B1G2GM9NG0-dsn.algolia.net" rel="preconnect" />

Mitigate the impact of a slow network on your app

Since Algolia is a hosted search API, the search experience will be affected if the network is slow. This guide shows you how to improve the user’s perception of search despite adverse network conditions.

Add a loading indicator

Consider a user accessing your app in a subway:

  1. They type some characters
  2. Nothing happens
  3. They wait, but still, nothing happens

However, you can enhance the user experience by displaying a loading indicator to indicate something is happening.

To display a loading indicator in the SearchBox, use the showLoadingIndicator option. The indicator will display slightly after the last query has been sent to Algolia. Change the duration of the delay with stalledSearchDelay (on the instantSearch widget).

For example:

1
2
3
4
5
6
7
import { InstantSearch, SearchBox } from 'react-instantsearch-dom'

const App = () => (
  <InstantSearch indexName="instant_search" searchClient={searchClient}>
    <SearchBox showLoadingIndicator />
  </InstantSearch>
)

Make your own loading indicator

You can also use the loading indicator with other components through the StateResults connector. The following example shows how to make a custom component that writes Loading... when search stalls. If network conditions are optimal, users won’t see this message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {
  InstantSearch,
  SearchBox,
  connectStateResults,
} from 'react-instantsearch-dom'

const LoadingIndicator = connectStateResults(({ isSearchStalled }) =>
  isSearchStalled ? 'Loading...' : null
)

const App = () => (
  <InstantSearch indexName="instant_search" searchClient={searchClient}>
    <SearchBox />
    <LoadingIndicator />
  </InstantSearch>
)

Debouncing

Another way of improving the perception of performance is by preventing lag. Although the default InstantSearch experience of generating one query per keystroke is usually desirable, this can lead to a lag in the worst network conditions because browsers can only make a limited number of parallel requests. By reducing the number of requests, you can prevent this lag.

Debouncing limits the number of requests and avoid processing non-necessary ones by avoiding sending requests before a timeout.

Implement debouncing at the SearchBox level with the useSearchBox() connector. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import React, { Component } from 'react'
import { InstantSearch, Hits, connectSearchBox } from 'react-instantsearch-dom'

class SearchBox extends Component {
  timerId = null

  state = {
    value: this.props.currentRefinement,
  }

  onChangeDebounced = (event) => {
    const { refine, delay } = this.props
    const value = event.currentTarget.value

    clearTimeout(this.timerId)
    this.timerId = setTimeout(() => refine(value), delay)

    this.setState(() => ({
      value,
    }))
  }

  render() {
    const { value } = this.state

    return (
      <input
        value={value}
        onChange={this.onChangeDebounced}
        placeholder="Search for products..."
      />
    )
  }
}

const DebouncedSearchBox = connectSearchBox(SearchBox)

const App = () => (
  <InstantSearch indexName="instant_search" searchClient={searchClient}>
    <DebouncedSearchBox delay={1000} />
    <Hits />
  </InstantSearch>
)

Optimize build size

InstantSearch supports dead code elimination through tree shaking, but you must follow a few rules for it to work:

  • Bundle your code using a module bundler that supports tree shaking with the sideEffects property in package.json, such as Rollup or webpack 4+.
  • Make sure you pick the ES module build of InstantSearch by targeting the module field in package.json (resolve.mainFields option in webpack, mainFields option in @rollup/plugin-node-resolve). This is the default configuration in most popular bundlers: you only need to change something if you have a custom configuration.
  • Keep Babel or other transpilers from transpiling ES6 modules to CommonJS modules. Tree shaking is much less optimal on CommonJS modules, so it’s better to let your bundler handle modules by itself.

If you’re using Babel, you can configure babel-preset-env not to process ES6 modules:

1
2
3
4
5
6
7
8
9
10
11
// babel.config.js
module.exports = {
  presets: [
    [
      'env',
      {
        modules: false,
      },
    ],
  ],
}

If you’re using the TypeScript compiler (tsc):

1
2
3
4
5
6
// tsconfig.json
{
  "compilerOptions": {
    "module": "esnext",
  }
}

Troubleshooting

To check if tree shaking works, try to import InstantSearch into your project without using it.

1
import 'react-instantsearch-dom' // Unused import

Build your app, then look for the unused code in your final bundle (for example, “InstantSearch”). If tree shaking works, you shouldn’t find anything.

Caching

Caching by default (and how to turn it off)

By default, Algolia caches the search results of the queries, storing them locally in the cache. This cache only persists during the current page session, and as soon as the page reloads, the cache clears.

Suppose the user types a search (or part of it) that has already been entered. In that case, the results will be retrieved from the cache instead of requesting them from Algolia, making the app much faster.

While it’s a convenient feature, sometimes you may want to clear the cache and make a new request to Algolia. For instance, when changes are made to some records in your index, you should update your app’s frontend to reflect that change (and avoid displaying stale results retrieved from the cache).

If you set the refresh() prop on the instantsearch component to true, it will clear the cache and trigger a new search.

When to discard the cache

Consider discarding the cache when your app’s data is updated by:

  • Your users (for example, in a dashboard). In this case, refresh the cache based on an app state, such as the last user modification.
  • Another process you don’t manage (for example, a cron job that updates users inside Algolia). In this case, you should refresh your app’s cache periodically.

Refresh the cache triggered by a user action

The following code triggers a refresh based on a user action (such as adding a new product or clicking a button).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React, { Component } from 'react'
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'

class App extends Component {
  state = {
    refresh: false,
  }

  refresh = () => {
    this.setState({ refresh: true }, () => {
      this.setState({ refresh: false })
    })
  }

  render() {
    return (
      <InstantSearch
        indexName="instant_search"
        searchClient={searchClient}
        refresh={this.state.refresh}
      >
        <SearchBox />
        <button onClick={this.refresh}>Refresh cache</button>
        <Hits />
      </InstantSearch>
    )
  }
}

Refresh the cache periodically

You can set an interval to determine how often the app clears the cache. Use this approach if you can’t trigger cache clearance based on user actions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { Component } from 'react'
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'

class App extends Component {
  state = {
    refresh: false,
  }

  componentDidMount() {
    this.interval = setInterval(
      () =>
        this.setState({ refresh: true }, () => {
          this.setState({ refresh: false })
        }),
      5000
    )
  }

  componentWillUnmount() {
    clearInterval(this.interval)
  }

  render() {
    return (
      <InstantSearch
        indexName="instant_search"
        searchClient={searchClient}
        refresh={this.state.refresh}
      >
        <SearchBox />
        <Hits />
      </InstantSearch>
    )
  }
}

If you need to wait for an action from Algolia, use waitTask to avoid refreshing the cache too early.

Queries per second (QPS)

Search operations aren’t limited by a fixed “search quota”. Instead, they’re limited by your plan’s maximum QPS and operations limit.

Every keystroke in InstantSearch using the SearchBox counts as one operation. Then, depending on the widgets you add to your search interface, you may have more operations being counted on each keystroke. For example, if you have a search interface with a SearchBox, a HierarchicalMenu, and a RefinementList, then every keystroke triggers one operation. But as soon as a user refines the HierarchicalMenu or RefinementList, it triggers a second operation on each keystroke.

If you experience QPS limitations, consider implementing a debounced SearchBox.

Did you find this page helpful?