Skip to content

Provide init/destroy callbacks to $state #16298

@anthumchris

Description

@anthumchris

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

Working REPL example

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions