ctrlaltdelme's avatar

Inertia Shared Data Best Practice?

Inertia's docs mention to use shared data sparingly since everything is brought to the page with each request. I'm currently making a database query to obtain post categories to display them in my Layout sidebar on every page. Using shared data just seemed obvious at first. But seeing the warning on Inertia's docs that I missed initially makes me question whether this is the best way to do this.

Are there other options within Inertia/Laravel to query the DB and have that data available to my Layout?

0 likes
2 replies
JussiMannisto's avatar
Level 50

If you need to list the post categories on every page, then yes, sharing them is necessary. The warning is only against unnecessary sharing of data, since you can always pass page-specific props from the controller.

If they're only used on a subset of all pages, you can create a separate middleware where you share them with Inertia::share(). You can then apply it to only the necessary route groups.

Either way, post categories doesn't sound like a lot of data, so sharing them will not impact performance in any meaningful way.

If there were tons of categories and fetching them were an expensive DB operation, you could combine lazy loading and caching on the backend, together with partial reloads on the front end. But it's not necessary here. You might still want to cache them for a few seconds, though, if your site has a lot of traffic and they're fetched from the DB.

1 like

Please or to participate in this conversation.