1

I have a <Highlight> component that renders text highlights. Currently, it takes a Zustand store as a prop (but I would like to move that store inside the component). Let's call this storeA.

There are many types of highlights; I want to be able to "plug these in" on a per-usage basis, like <Highlight kinds={[red, blue]}> in one place and <Highlight kinds={[red, green]}> in another. (I'm using props for illustration; my question is about how I should structure the API, and props may not be the answer.) I need to do this

  • without breaking the rules of Hooks; so I should be able to do <Highlight kinds={kinds}> and change the length of kinds without breaking things
  • without centralizing all the different kinds inside <Highlight>

The various kinds are computed in different ways:

  • Red highlights are derived from the state of storeA;
  • Blue highlights are derived from the state of a different Zustand store storeB;
  • Green highlights are derived from query parameters via next/router's useRouter()

What I'm currently doing is giving the Blue and Green highlight providers access to storeA, and doing something like

storeA.setState(prev => ({
  highlights: {
    ...prev.highlights,
    green: newGreenHighlights
  }
});

The main issue I'm having with this approach is that the Blue and Green providers need to call this setState in a useEffect or imperative event handler. I would prefer to have them derive state from a Hook call.

What is a clean way to structure this API?

Yuri Sulyma
  • 393
  • 1
  • 12

0 Answers0