DEV Community

Svelte: Best practice to combine $derived and $state

Max Core on October 04, 2025

First approximation: let { data } = $props(); let posts = $derived.by(() => { let posts = $state(data.posts); return posts; }); ...
Collapse
 
webjose profile image
José Pablo Ramírez Vargas

What's the use case? What problem does this solve?

Collapse
 
dennis_h_proksch profile image
Dennis Proksch

Use case is e.g. if you want a filter on your website. Like you already have post but you set a filter like posts that include a certain word -> you don't want to alter the posts variable, but the "visiblePosts" one.

Another one (my current one) is when my API delivers several "clean" data endpoints that need to be combined into a frontend. With derived I can just listen to the "clean" data and use the data that fits my frontend best.

Collapse
 
maxcore profile image
Max Core • Edited

$derived is shallow reactive posts = new_value,
not deeply reactive posts.title = new_value,
unless you combine it with $state

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

I see. But this is rarely needed, I'd say. Only if you are modifying the derived value.

Anyway, thanks for clarifying.

Thread Thread
 
k776 profile image
Kieran Pilkington

"rarely needed" - Actually we were using props in $state throughout our app, and then the new warning against doing that showed up (which did infact reveal we had issues in our code). So our first pass was to change all our $state(prop) syntax to the syntax shown in the OP. Problem with OPs approach is that if you reassign the $dervied var, it would lose the $state aspect. So we ended up creating a box function that wraps it in a proxy with some checks and setter methods to prevent it from ever losing $state, but the whole thing is clunky. Ideally Svelte would support something natively ($derived.from(prop) or $derived.state(prop), or $state.from(prop), or something).

Thread Thread
 
webjose profile image
José Pablo Ramírez Vargas

Interesting. Indeed. Sounds like an inconsistency at the (Svelte) library level. You might want to start a discussion or an issue about it in Svelte's GH repository.

Collapse
 
opensas profile image
opensas

I did this small example
with just "let posts = $derived(data.posts)" it seems to work
I can't seem to reproduce the issue

see: svelte.dev/playground/f5645f6cf229...

Collapse
 
opensas profile image
opensas

could you please add a couple examples and explanation showing the problem you are trying to solve?
I still find confusing to understand when stuff is reactive or not

Collapse
 
maxcore profile image
Max Core • Edited

Hi

$derived is shallow reactive posts = new_posts,
not deeply reactive posts.title = new_title,
unless you combine it with $state