Cost of stateful components confusion

In my liveview I have a component where I need to send the user id.

<%= live_component MyComponent, id: "foobar", current_user: @current_user %>

My question: is it cheaper to send the whole @current_user struct or should I just send the field I’m interested in.

<%= live_component MyComponent, id: "foobar", current_user: @current_user %>

# vs

<%= live_component MyComponent, id: "foobar", current_user_id: @current_user.id %>

Which one is better for performance? The official documentation is confusing me.

Therefore it is your responsibility to keep only the assigns necessary in each component. For example, avoid passing all of LiveView’s assigns when rendering a component:

<.live_component module={MyComponent} {assigns} />

Instead pass only the keys that you need:

<.live_component module={MyComponent} user={@user} org={@org} />

Luckily, because LiveViews and LiveComponents are in the same process, they share the data structure representations in memory. For example, in the code above, the view and the component will share the same copies of the @user and @org assigns.

The liveview and the livecomponent use the same process and share memory but still don’t pass in structs? Appreciate some clarity, thanks!

1 Like

@sergio it isn’t about memory usage, it’s about avoiding re-rendering. If you’re going to use the user, then pass in the user. But if you have 10 assigns, and your component only uses 2 of those assigns, don’t pass in all 10. If you change any of the 10, it will force a re-render. If you only pass in the 2 assigns that you need, then you only get a re-render of that component if those two change.

6 Likes

you can pass anything you want to the live component, but only hold on to the state you care about. By default update/2 does {:ok, assign(socket, assigns)}, so it would store current_user, but if you don’t need it in the template, you can only grab the id and put that in assigns, and/or you can mark current_user as a temporary_assign in the component mount/2 and happily use @current_user in the template without keeping it in memory. When optimizing for memory usage, In general you want to mark assigns as temporary that you don’t need to keep around, just be sure to check the docs on the caveats if you need to recompute the assign later.

3 Likes

Thanks guys, appreciate the further clarity!