Build a React app with fast indexing and instant inventory updates

A friend and I recently brainstormed how we could support our local bands while Covid continued to limit their opportunities to play live shows. We came up with an idea for a website where bands could sell limited-edition poster prints and t-shirts. The website would be designed to create a sense of community and urgency by promoting new items as they became available on social media, also known as ‘drops’, similar to what the fashion brands and the sneaker world have succeeded in doing. 

We chose Algolia as our main tool because it offers front-end libraries that make it easy to spin up an ecommerce site with a top-tier search and discovery experience for customers. We decided to  leverage the search capabilities and modularity of InstantSearch for React. Here’s a rough diagram of what we wanted to build:

The challenge of instant inventory updates

The goal of the project was to create a sense of urgency when new products get released. The technical challenge, therefore, was to display an up-to-the-second inventory to our users. Searching and retrieving information from Algolia indexes is lightning fast, providing as-you-type instant search results. On the other hand, updating the data on the back end can take a little more time. However, we discovered that if we were to update our index every time the inventory changed, it would have slowed down both the search results and the rendering times of some front-end components.

We’re going to look at how we were able to use and adapt InstantSearch to build an almost up-to-the-second search capability for an ecommerce website.

Using Algolia Widgets for InstantSearch

Algolia InstantSearch offers incredibly fast search results, and it allowed us to scan through designs quickly to create the desired sense of urgency. The Autocomplete functionality inside InstantSearch added discovery, as users see suggestions they might not have considered. 

I wanted to build the site in React because it offers good choices for ecommerce design and cross-platform compatibility. InstantSearch for React is a library of pre-built front-end React widgets that make getting started with a site layout a very quick process. The component diagram above maps well to a few of these widgets:

  • SearchBox and RefinementList are in the upper left in our mockup above
  • Autocomplete feeds the “Are you looking for…” suggestions in the upper right 
  • Hits is the list of search results on the left

If you don’t have an Algolia Index, create an account and app. We created a <SearchBox> component that contains the first three widgets (SearchBox, RefinementList, and Autocomplete), and a <Hits> component for the Hits widget, displaying our list of products. The <ProductDetail> component uses our own data and code, since it doesn’t come from the Algolia index.

We had a problem with this design, though, which is that it requires us to update and retrieve data from our Algolia index constantly. As we mentioned above, Algolia indexes are optimized for retrieval. Their engine prioritizes search, with fast indexing a close second. We didn’t want to flood the server with index updates which could slow down the search, the rendering of <Hits>, or limit the functionality in <SearchBox>, all of which depend on super-fast data retrieval with every keystroke. We came up with a solution – separate our inventory data updates from our search processing, so that we could update the inventory without touching our main index. 

We went back to our site mock-up, and found we could work around this problem by customizing the InstantSearch widgets

Create a Second Algolia Index for Inventory

The solution that lets us have both as-you-type instant search results and instant inventory is to have two separate Algolia indexes. If you don’t already have an Algolia Index, create an account and app.

One of the indexes is a typical product index. The JSON looks like this:

  "objectID": 42,
  "title": "Return to Paranormal",
  "band": “Out In The Cold”,
  "designer": “Jamie Deer”,
  "introduction_date": “2021-09-23T18:25:43.511Z”,
  "sizes": [“adults”, “kids”, “pets”],
  "_tags": ["Seattle", "aliens", “punk”]

This is just a simple record. Eventually, we will include more information in the index, such as links to the band and designer websites, image URLs, etc. 

The second index is simpler:

   “objectID”: 42,
   “remaining_editions”: 18

Now we can update the smaller inventory index without impacting the main index used for <Hits>.

Using two indexes also requires splitting up the UI into two separate components for each Hit result, but it’s a simple adjustment:

We moved the remaining_editions number out of the <Hits> component and into its own separate custom widget, which we rendered as a separate component, called <Inventory>. Both indexes, and both components, use the same objectID

It’s important to note that we’re not making <Inventory> a child of <Hits>, because we need to keep the rendering of these two components separate. That’s why the <SearchPage> component holds <SearchBox>, <Hits>, <Inventory>, and <ProductDetail> at the same level.

Using React Hooks to Keep Everything Available

As you might have noticed, we rely on three data sources:

  1. Algolia Index (on Algolia’s servers) – This index provides the data to populate the <Hits> and <SearchBox> components. The data in here is an extract from our back-office database (3), which gets updated regularly when product listings change.
  2. Algolia Inventory Index (on Algolia’s servers)  – This index provides the updated remaining_editions attribute displayed in the <Inventory> component. The remaining_editions attribute comes from our back-office database (3).
  3. Our back-office database (on our servers) – We maintain a detailed back-office database of products, which includes lengthier product descriptions and purchase data. We pull inventory changes from this database and update the <ProductDetail> component asynchronously, with the exception of remaining_editions, which is displayed to the <Inventory> component.

We have two goals in this application: one, to offer “instant” inventory numbers, and two, to keep as-you-type instant search results enabled at all times. Here’s how we accomplish both goals.

InstantSearch Never Slows Down

Keeping InstantSearch fully available is non-negotiable. Customers can understand a couple of seconds of delay in inventory, but they won’t tolerate slow or glitchy search functionality. Here’s how we structure this part:

  • We use a pretty standard implementation of InstantSearch, with one change that requires us to connect a custom component for Hits
  • In our <SearchPage> component, we use React state hooks and create a setter method for setObjectIDs that gets passed to the <Hits> component. 
  • As Hits render, we capture the objectIDs in an array with a handler method, then pass that back up to <SearchPage>
  • In terms of managing asynchronous API calls, this is our first priority, so the only thing the Hits widget is waiting for is the InstantSearch API. We could have managed this with a useEffect() hook in <Hits>, but Algolia provides a method in InstantSearch that achieves the same goal: onSearchStateChange

These steps get us the information we need from <Hits> without interrupting the UI or data flow of the as-you-type InstantSearch functionality – we just plug in to the middle with our connected component and use a built-in method to trigger updates.

Code for SearchBox.js:

import { InstantSearch } from 'react-instantsearch-dom';
import SearchBox from './SearchBox.js';
import CustomHits from './Hits.js';
import Inventory from './Inventory.js';
import ProductDetail from './ProductDetail.js';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function SearchPage() {
 const [objectIDs, setObjectIDs] = useState([]);
 const [selectedObject, setSelectedObject] = useState({
   objectID: null,
 return (
         query: '',
       onSearchStateChange={searchState => {
         if (searchState) {
       <SearchBox />
       <Inventory objectIDs={objectIDs} />
       <ProductDetail selectedObject={selectedObject} />
export default SearchPage;

Code for Hits.js`:

import React from 'react';
import PropTypes from 'prop-types';
import { connectHits } from 'react-instantsearch-dom';
function Hits({ hits, objectIDs, setObjectIDs }) {
 const handleSearch = () => { => objectIDs.push(hit.objectID));
 return (
     { => (
       <li key={hit.objectID}>{}</li>
Hits.propTypes = {
 hits: PropTypes.arrayOf(PropTypes.object),
 objectIDs: PropTypes.arrayOf(PropTypes.string),
 setObjectIDs: PropTypes.func,
const CustomHits = connectHits(Hits);
export default CustomHits;

“Instant” inventory updates are close to real-time

Now that we are set up to capture the objectIDs, we need to set up our inventory updates. There are three separate situations where we will be calling our inventory index: two for the <Inventory> component, and one within the <ProductDetail> component. 

In order to display up-to-the-minute inventory information, we need two data points: the array of objectIDs for the current results in <Hits>, and the most recent number from our inventory index. The objectIDs are now held in <SearchPage>, and update each time the searchState changes, so passing them down into <Inventory> is easy. To get the info from our inventory index, we use another built-in Algolia method: index.getObjects(). This lets us go directly to the objects we want without having to create another InstantSearch instance. 

Note that as of algoliasearch@4.0.0, the getObject() and getObjects() methods are not available in the lite build, which is the default import – you’ll just need to update the import statement.

Once we make the initial connection, setting up the second call to the inventory index is simple. We added a setInterval() function inside a useEffect() hook to call the inventory index every two seconds. That way, even if a user doesn’t update their search term, inventory numbers will continue to refresh rapidly, ensuring real-time inventory. We may adjust that interval in production, but that seemed fast enough for our purposes.

Code for Inventory.js:

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import algoliasearch from 'algoliasearch';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function Inventory({ objectIDs }) {
 const index = searchClient.initIndex('inventory_index');
 let results = index.getObjects(objectIDs);
 useEffect(() => {
   const timer = setInterval(() => {
     results = index.getObjects(objectIDs);
   }, 2000);
   return () => clearTimeout(timer);
 }, []);
 return (
     { => (
       <li key={result.objectID}>Remaining: {result.remaining_editions}</li>
Inventory.propTypes = {
 objectIDs: PropTypes.arrayOf(PropTypes.string),
export default Inventory;

The code inside the <ProductDetail> component is much the same. That component will fetch most of its data from our product database, a non-Algolia data source. For the inventory number, it will call the inventory_index just as above, using only the objectID of the selectedObject. With this design, there should only be a very small lag, no more than two seconds, between the inventory number shown next to the product result in <Hits> and the inventory number in the <ProductDetail> component. With this in place, <ProductDetail> will always show the more recent data. 

Now we have a <SearchPage> that shows near-instant inventory updates, while still allowing full use of as-you-type instant search results.

We envisioned this project as a way for independent artists and musicians to connect their social media presences with an ecommerce platform. As music fans ourselves, we’ve missed the sense of community and energy of the local music scene over the last couple of years. Our hope is that this site design will feel authentic and exciting enough to capture some of that energy. 

Algolia’s quick-to-implement widgets and adaptable components make it easy to spin up prototypes. You may have other ideas of where an ‘instant inventory’ would be useful – Black Friday sales, maybe! We hope to hear about what you build with Algolia, and how it transforms your projects!

About the authorJulia Seidman

Julia Seidman

Developer Educator

Recommended Articles

Powered by Algolia AI Recommendations

Adding trending recommendations to your existing e-commerce store

Adding trending recommendations to your existing e-commerce store

Ashley Huynh

Ashley Huynh

Building a multi-lingual rhyming dictionary with Wiktionary and Algolia — part 2, the GUI

Building a multi-lingual rhyming dictionary with Wiktionary and Algolia — part 2, the GUI

Jaden Baptista

Jaden Baptista

Technical Writer
Part 4: Supercharging search for ecommerce solutions with Algolia and MongoDB — Frontend implementation and conclusion

Part 4: Supercharging search for ecommerce solutions with Algolia and MongoDB — Frontend implementation and conclusion

Soma Osvay

Soma Osvay

Full Stack Engineer, Starschema