-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Description
Describe the problem
I would like to used shared/global $state across multiple components and centrally manage the initialization and cleanup/teardown of that state on first/last use, similar to using Svelte 4 stores and their StartStopNotifier.
My goal is to provide developers with declarative, decoupled logic and state for their components and eliminate their explicit use of lifecycle hooks (onMount, onDestroy) by optimizing $state behind-the-scenes. This allows me to implicitly improve runtime performance and reduce memory usage by reading/writing large amounts of previously-fetched data to browser disk storage when $state is first/last used.
related: #11980
Describe the proposed solution
Provide init/destroy callbacks to $state, similar to the StartStopNotifier used in Svelte stores. This also assists us when migrating from Svelte 4 stores to Svelte 5 $state Runes.
const myState = $state({
loading: false,
data,
error,
}, initDestroy)
function initDestroy(state) {
console.log('init')
return () => {
console.log('destroy')
state.loading = false
state.data = null
state.error = null
}
}Importance
would make our lives easier