Guides / Building Search UI / Going further

Preparing 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.

You can use a preconnect link to carry out the handshake immediately after the page has loaded, 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 application

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

Adding a loading indicator

Imagine a user using your search in a subway, by default this is the kind of experience they will get:

  • type some characters
  • nothing happens
  • still waiting, still nothing

At this point, the user is really wondering what is happening. You can start enhancing this experience by providing a visual element to hint that something is happening: a loading indicator.

And for this, React InstantSearch provides an option on the SearchBox called showLoadingIndicator. The indicator will appear in the SearchBox. It will also be triggered a little after the last query has been sent to Algolia. This prevents the element to flicker.

The delay can be configured using the stalledSearchDelay on the InstantSearch widget.

Here is an 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

The mechanism of the loading indicator is also available through the StateResults connector. You can use it to render a component based on the loading conditions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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>
);

This 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.

Debouncing

Another way of improving the perception of performance is to try to prevent 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 done, you can prevent this lag.

Debouncing is a way to limit the number of requests and avoid processing non-necessary ones by avoiding sending requests before a timeout.

There is no built-in solution to debounce in React InstantSearch. You can implement it at the SearchBox level with the help of the SearchBox connector. Here is an 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

React 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 via the sideEffects property in package.json, such as Rollup or webpack 4+.

  • Make sure to pick the ES module build of React 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, so you shouldn’t need to change anything unless 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 we recommend that you 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,
          },
        ],
      ],
    };
    

    or if you are using the TypeScript compiler (tsc):

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

Troubleshooting

To ensure tree shaking is working, you can try to import React InstantSearch in your project without using it.

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

Build your application, 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 get rid of it)

By default, Algolia caches the search results of the queries, storing them locally in the cache. If the user ends up entering a search (or part of it) that has already been entered previously, the results will be retrieved from the cache, instead of requesting them from Algolia, making the application much faster. Note that the cache is an in-memory cache, which means that it only persist during the current page session. As soon as the page reloads the cache is cleared.

While it is a very convenient feature, in some cases it is useful to have the ability to clear the cache and make a new request to Algolia. For instance, when changes are made on some records on your index, you might want the frontend side of your application to be updated to reflect that change (in order to avoid displaying stale results retrieved from the cache).

To do so, there is a prop on the InstantSearch component called refresh. You can set it to true, it clears the cache and triggers a new search.

There are two different use cases where you would want to discard the cache:

  • your application data is being directly updated by your users (for example, in a dashboard). In this use case you would want to refresh the cache based on some application state such as the last modification from the user.
  • your application data is being updated by another process that you don’t manage (for example a CRON job that updates users inside Algolia). For this you might want to periodically refresh the cache of your application.

Refresh the cache triggered by an action from the user

If you know that the cache needs to be refreshed conditionally after a specific event, then you can trigger the refresh based on a user action (adding a new product, clicking on a button for instance).

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>
    );
  }
}

See a live example on Storybook. You can find the source code of the example on GitHub.

Refresh the cache periodically

You also have the option to setup an given period of time that will determine how often the cache will be cleared. This method will ensure that the cache is cleared on a regular basis. You should use this approach if you cannot use a user action as a specific event to trigger the clearing of the cache.

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>
    );
  }
}

Note that if you need to wait for an action from Algolia, you should use waitTask to avoid refreshing the cache too early.

See a live example on Storybook. You can find the source code of the example on GitHub.

Queries Per Second (QPS)

Search operations are not limited by a fixed “search quota”. That being said, they are limited by the maximum QPS and the operations limit of your plan.

Every time you press a key in InstantSearch using the SearchBox, we count one operation. Then, depending on the widgets you will be adding to your search interface, you may have more operations being counted on each keystroke. For example, if you have a search made out of a SearchBox, a Menu, and a RefinementList, then every keystroke will trigger one operation. But as soon as a user refines the Menu or RefinementList, it will trigger a second operation on each keystroke.

A good rule to keep in mind is that most search interfaces using InstantSearch will trigger one operation per keystroke. Then every refined widget (clicked widget) will add one more operation to the total count.

In case you have issue with the QPS you can consider implement a debounced SearchBox.

Did you find this page helpful?