React - retain refinement state when component dismounts

I’m using React InstantSearch.

I have a left sidebar with a RefinementList component. On narrow/mobile screens, I have the RefinementList component in a sliding sidebar that overlays search results.

The refinement state resets when the sliding sidebar is closed.

What is the best practice to retain refinement state when a component dismounts?

Hi Dom!

In InstantSearch, each widget hold a piece of related state. For example, the SearchBox holds the current query, meaning that we always need to have one in the search experience, even if it doesn’t render anything.

In your case, you have a RefinementList in a sidebar that closes, unmounting the widget, causing the refinements to disappear. This is expected.

There are several ways of handling this: you can either avoid unmounting, or use virtual widgets.

Avoid unmounting

In this scenario, you never unmount the RefinementList. Instead of removing your left sidebar from the component structure, you repurpose it into the overlaying sliding sidebar, with CSS, using media queries.

This is the most lightweight option, as it doesn’t require any extra JavaScript, nor does it affect your component tree. In most cases, this is the recommended option.

This is what we did in our e-commerce demo using React InstantSearch. The sidebar on the left with multiple RefinementLists transforms into a sliding overlay on narrow screens, with CSS only.

Use virtual components

What we call virtual widgets are InstantSearch widgets that don’t render anything, using connectors. They’re useful for controlling state programmatically. Instead of letting your RefinementList control the UI and the state, you build your own refinement UI and programmatically manage state, then pass it down to a renderless RefinementList via the defaultRefinement prop.

This is a heavier solution, which I would recommend only if the first one has a technical limitation within your use case that you can’t circumvent.

Thank you @sarah.dayan ! I went with the media query option and it works great. Appreciate the detailed response.