You want to populate a select box using server data but wonder what is the best way to do it?
Hard coding the data is not an option because it is too dynamic.
The docs are suggesting to use a fetcher but this means an API call every time the select is rendered which might not be ideal.
useMatches
can solve the problem
Load the data in a root loader and use useMatches
to access the data in the Select component.
In your root loader get the options and return the in the payload.
Then in the Select component use the data
This pattern ensures that the data will be fetched only once in the root route and can be consumed all over the app with ease.
useMatches
lets us access the data of all rendered routes at all times, and in our case, in the select component, wherever it is rendered.
Gotchas:
- the match
id
will change according to the routes the loader is attached to. (see https://remix.run/docs/en/main/hooks/use-matches) await
ing the data in the root loader will block the page from rendering which is less ideal for an element that is not interactive until later in time. An improvement will be to use defer to prevent the blocking.
Subscribe to the newsletter to hear more about these topics!