reset state without using $effect? #16206
-
First of all, sorry if such a question has already been asked, but I have not found a similar discussion. $: tabId, (pageIndex = 0), (items = []); Now I want to write it in Svelte 5, but the only thing I was able to produce is: $effect(() => {
if (tabId) {
pageIndex = 0;
items = [];
}
}); However, When not to use $effect says that |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You could try to use |
Beta Was this translation helpful? Give feedback.
If you want deep reactivity on the items you would need to wrap the array in
$state
.This also splits logic that is coupled, so I probably would not go with this if events or function bindings cannot be used. (You could maybe bundle both variables into a single object, though that might not be the logical thing to do depending on context.)
Note that just using an
$effect
for this is really is not much of an issue. For certain things, like synchronizing a local, mutable variable from a prop,$effect
has actually been recommended for some time (now that$derived
can be overwritten, you don't need that any more).So compared to the
$derived
approach, I find the$effect
code to be cleaner, an…