Provide init/destroy callbacks to `$state` · Issue #16298 · sveltejs/svelte · GitHub | Latest TMZ Celebrity News & Gossip | Watch TMZ Live
Skip to content

Provide init/destroy callbacks to $state #16298

Closed as not planned
Closed as not planned
@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

      TMZ Celebrity News – Breaking Stories, Videos & Gossip

      Looking for the latest TMZ celebrity news? You've come to the right place. From shocking Hollywood scandals to exclusive videos, TMZ delivers it all in real time.

      Whether it’s a red carpet slip-up, a viral paparazzi moment, or a legal drama involving your favorite stars, TMZ news is always first to break the story. Stay in the loop with daily updates, insider tips, and jaw-dropping photos.

      🎥 Watch TMZ Live

      TMZ Live brings you daily celebrity news and interviews straight from the TMZ newsroom. Don’t miss a beat—watch now and see what’s trending in Hollywood.