Svelte
svelte/derived-not-effect
A value computed from state is a $derived, not a $state that an $effect keeps in sync.
umiarkowanastatycznefe-svelte
Dlaczego
An effect runs after the update, so the synced value is stale for one render, the component updates twice, and two pieces of state can drift apart. Effects that write state are the usual start of update loops (effect_update_depth_exceeded) and make the data flow hard to follow.
Poprawka
Declare the value with $derived(expression), or $derived.by(() => { ... }) for several statements. Deriveds can be overridden by assignment (an optimistic value) and recompute when their inputs change. Keep $effect for work outside Svelte: a canvas, a third-party widget (better: {@attach}), analytics.
Przykłady
<!-- bad -->
<script>
let { items } = $props()
let visible = $state([])
$effect(() => { visible = items.filter((item) => !item.hidden) })
</script>
<!-- good -->
<script>
let { items } = $props()
let visible = $derived(items.filter((item) => !item.hidden))
</script>Źródła
Fakty
- Identyfikator
svelte/derived-not-effect- Waga
- umiarkowana
- Sprawdzanie
- statyczne sprawdzane w kodzie źródłowym przez
audit - Dotyczy plików
svelte- Tylko w projektach z
sveltesveltekit- Uczy jej skill
fe-svelteSvelte components- Od wersji
- 0.1.0
Przeczytaj w terminalu
npx github:dawidolko/frontend-skills explain svelte/derived-not-effect