We are integrating React Instant Search in a next.js application. We've noticed that an Algolia search request is being called on _every_ page render (not just refresh, every render) which is racking up hundreds of requests per session even when the user never types a search query! This is obviously not intended behavior.
Digging a layer deeper, I learned about the default caching behavior of react instant search as described here. I modified the caching behavior to use browser local storage cache and then the search started working as I would expect it to (i.e. it makes a request _only once_ at initial load and then the request results are cached so it doesn't make another request until the user explicitly creates a new search)
However, I'd rather use the default in-memory cache and I do not understand why it is not working.
So some questions to help troubleshoot:
Code with working cache:
const searchClient = algoliasearch(algoliaAppId, apiKey, {
responsesCache: createFallbackableCache({
caches: [
createBrowserLocalStorageCache({ key: `${version}-${algoliaAppId}` }),
createInMemoryCache(),
],
}),
})
Code without working cache:
const searchClient = algoliasearch(algoliaAppId, apiKey)
This also does not work:
const searchClient = algoliasearch(algoliaAppId, apiKey, {
responsesCache: createInMemoryCache()
})
My environment:
Note:
apiKey is being generated server side to embed user-specific filters into the search requests - not sure if this is relevant. Thanks for any help.
Do you have a sandbox where we can see how you implemented React InstantSearch in multiple pages? I'm thinking possibly a new instance of algoliasearch is created on every render / page and thus doesn't read the cache?
@Haroenv I believe you are correct! I don't have a sandbox but thanks for your input.
Maybe this is obvious to most people and it is not a common issue, but it might be worth noting somewhere in the documentation that this behavior can happen if a new instance is created on every render. A sentence about this somewhere in the docs would have saved me half a day of trouble shooting.
For example, this page exists and it was one of the first things I came across when troubleshooting. It could be mentioned here or on another FAQ page like this.
Thanks again.
Good point, I'll add something around that here: https://www.algolia.com/doc/guides/building-search-ui/troubleshooting/faq/react/
I was thinking:
- question: Why does the search client cache not work?
answer: |
It's possible that you recreate the search client over every render. The cache isn't shared across different instances of `algoliasearch`, so make sure that you create the search client just once.
馃憤 I'd go a little more specific on the question:
Why does the search client cache not preventing redundant requests to Algolia?