Skip to main content
The InstantSearch instance is the core object that manages your search UI. It coordinates widgets, manages search state, and communicates with your search backend.

Creating an instance

InstantSearch requires a search client and an index name to initialize:
import instantsearch from 'instantsearch.js';
import algoliasearch from 'algoliasearch/lite';

const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');

const search = instantsearch({
  indexName: 'products',
  searchClient,
});

Configuration options

The InstantSearch instance accepts several configuration options defined in InstantSearchOptions (from /home/daytona/workspace/source/packages/instantsearch.js/src/lib/InstantSearch.ts:62-195):

Required options

searchClient
SearchClient
required
The search client to connect to your search backend. This must implement a search method.
const searchClient = algoliasearch('appId', 'apiKey');
indexName
string
The name of the main index. If no indexName is provided, you must manually add an index widget.
indexName: 'products'

Optional options

initialUiState
UiState
Provides an initial state to widgets. The state is only used for the first search.
initialUiState: {
  products: {
    query: 'laptop',
    refinementList: {
      brand: ['Apple', 'Samsung']
    }
  }
}
routing
RouterProps | boolean
Enable URL routing to save UI state in the URL. Pass true for default behavior or an object for custom configuration.
routing: true
// or
routing: {
  router: historyRouter(),
  stateMapping: simpleStateMapping()
}
See the routing documentation for details.
insights
InsightsProps | boolean
default:"false"
Enable the Insights middleware to automatically send view and click events.
insights: true
stalledSearchDelay
number
default:"200"
Time in milliseconds before a search is considered stalled.
stalledSearchDelay: 500
onStateChange
function
Function called when the state changes. Using this makes the instance controlled.
onStateChange({ uiState, setUiState }) {
  // Modify or validate the state
  setUiState(uiState);
}
numberLocale
string
Locale for formatting numbers, passed to Number.prototype.toLocaleString().
numberLocale: 'en-US'
future
object
Feature flags for upcoming changes:
future: {
  preserveSharedStateOnUnmount: true
}

Instance methods

The InstantSearch instance exposes several methods (from /home/daytona/workspace/source/packages/instantsearch.js/src/lib/InstantSearch.ts:211-900):

Managing widgets

addWidgets
(widgets: Widget[]) => InstantSearch
Adds widgets to the search instance. Widgets can be added before or after the instance has started.
search.addWidgets([
  searchBox({ container: '#searchbox' }),
  hits({ container: '#hits' })
]);
removeWidgets
(widgets: Widget[]) => InstantSearch
Removes widgets from the search instance.
search.removeWidgets([searchBoxWidget]);

Lifecycle methods

start
() => void
Starts the InstantSearch instance and triggers the first search. This must be called after adding widgets.
search.addWidgets([/* ... */]);
search.start();
dispose
() => void
Removes all widgets and stops the instance. The instance can be restarted later.
search.dispose();

State management

setUiState
(uiState: UiState | ((prev: UiState) => UiState)) => void
Sets the UI state and triggers a search. Accepts a state object or a function.
// Set state directly
search.setUiState({
  products: {
    query: 'laptop'
  }
});

// Update state functionally
search.setUiState((prevState) => ({
  ...prevState,
  products: {
    ...prevState.products,
    page: 2
  }
}));
getUiState
() => UiState
Returns the current UI state.
const currentState = search.getUiState();
console.log(currentState.products.query);
refresh
() => void
Clears the cache and triggers a new search.
search.refresh();

URL management

createURL
(state: UiState) => string
Creates a URL for the given state. Only available after start() is called.
const url = search.createURL({
  products: {
    query: 'laptop',
    page: 2
  }
});

Middleware

use
(...middleware: Middleware[]) => InstantSearch
Adds middleware to the InstantSearch lifecycle.
search.use(createInsightsMiddleware({ insightsClient }));
unuse
(...middleware: Middleware[]) => InstantSearch
Removes middleware from the instance.
search.unuse(insightsMiddleware);

Instance properties

status
'idle' | 'loading' | 'stalled' | 'error'
The current status of the search.
if (search.status === 'loading') {
  console.log('Search in progress...');
}
error
Error | undefined
The last error returned from the Search API. Cleared when the next valid response is received.
if (search.error) {
  console.error('Search error:', search.error.message);
}
helper
AlgoliaSearchHelper | null
The main search helper instance. Available after start() is called.
mainIndex
IndexWidget
The root index widget that contains all other widgets.

Events

InstantSearch extends EventEmitter and emits a render event after each search response:
search.on('render', () => {
  console.log('Search rendered');
});

search.on('error', (error) => {
  console.error('Search error:', error);
});

Type signature

The InstantSearch class is generic and accepts type parameters for custom UI state:
class InstantSearch<
  TUiState extends UiState = UiState,
  TRouteState = TUiState
>
This allows you to type your custom UI state:
type MyUiState = {
  products: {
    query?: string;
    page?: number;
    refinementList?: {
      brand?: string[];
    };
  };
};

const search = instantsearch<MyUiState>({
  searchClient,
  indexName: 'products',
});

Widgets

Learn about the widget system

Search state

Understanding UI state management

Routing

Synchronize state with URLs

Server-side rendering

Implement SSR with InstantSearch

Build docs developers (and LLMs) love