When changing routes in Next.js 14, the hits from useInfiniteHits() become an empty array []

Hi everyone,

I’ve been using react-instantsearch-nextjs with next.js 14, employing useInfiniteHits().

On a category page, when there are no products, hits returns an empty array , as expected. However, when I select another category page from the same page where products exist, hits also returns an empty array . After refreshing the page is the only time I receive hits with products.

Could someone help me understand this behaviour?


The behavior you’re experiencing with useInfiniteHits returning an empty array after switching categories within the same page in Next.js 14 is likely due to how Next.js handles client-side data fetching. Here’s a breakdown of the issue and potential solutions:

Understanding the Problem:

useInfiniteHits from react-instantsearch-nextjs relies on client-side state management to store search results.
Next.js 14 introduced changes to routing that might not trigger a complete re-render of the component using useInfiniteHits when switching categories on the same page.

Consequently, the component might not be aware of the new category selection and continues to display the previous empty results.


Force Re-render on Category Change:

Update your component to explicitly re-render when the category changes. You can achieve this by:
Using a state management library like Redux or Zustand to store the selected category and trigger a re-render when it changes.

Utilizing the useRouter hook from Next.js to listen marykayintouch for category changes in the URL and re-run the search query.

Clear Search State on Category Change:

You can clear the existing search state within useInfiniteHits when the category changes. This ensures a fresh search for the new category:

import { useInfiniteHits } from 'react-instantsearch';

function MyComponent() {
  const router = useRouter();
  const { category } = router.query;

  const { refine, ...rest } = useInfiniteHits({
    indexName: 'your_index_name',
    params: {
      facetFilters: [category], // Update with your category filtering logic

  useEffect(() => {
    refine(); // Trigger a new search on category change
  }, [category, refine]);

  // ... rest of your component logic

  return (
      {/* Your search results logic using rest */}

Consider using a loading indicator while the new search results are being fetched after a category change.

Explore the stale-while-revalidate revalidation strategy provided by Next.js for potentially caching search results while keeping them up-to-date.

I hope the information may help you.