Simplest pattern for stateless components which need to load data

I have the need for a component which, given an id, displays a user name. A stateless component would be perfect because it’s small, it’s used in a lot of places, and it doesn’t have state.

To render the component, data needs to be fetched from the db, given the id. After this fetch, no other state is maintained or used. I’ve started using live_component, but it doesn’t feel right to have all these stateful components around which don’t actually need it (and consuming resources). Is there a better pattern to make use of here?

Small follow-up, but related: All the live_components need a unique ID, which also makes this trickier since this component will possibly on the same page a few times. So solving this is also part of the problem (but i can work around it).

It sounds like maybe a plain function component is what you’re looking for.

Yeah you want to use :component instead of :live_component

For the sake of not mass-producing N+1 queries I’d strongly suggest not doing any db queries in function components. There’s a reason why live_components have a preload callback, but really it would be even better if you’d just load the name of the user id you have and supply that to templates instead of the raw id.


thanks for the responses.

I think a function based component is probably the best way forward. It feels like an anti-pattern to fetch data as part of render, but for this particular case, I think it’s ok. I think the approach I’ll take is to allow passing a user model or the id - and if the id is passed, then do the fetch on demand.