Skip to content

Request: $state.snapshot(prop) suppresses state_referenced_locally #17303

@sillvva

Description

@sillvva

Describe the problem

Currently the solution to assign the initial value of a prop to state is to use a comment to suppress the state_referenced_locally warning.

let { prop } = $props();

// svelte-ignore state_referenced_locally
let value = $state(prop);

Describe the proposed solution

Using $state.snapshot at the root level should suppress the warning, because it signals a clear intent that you want the initial value unchanged.

let { prop } = $props();

let value = $state($state.snapshot(prop));

https://svelte.dev/playground/27f442f9ce0a4e8aa5d8d21c802152d5?version=5.45.5

Use Case

An example use case in forms would be to store the initial data to compare it to the current form values and determine whether the form data has been mutated.

// Form.svelte
let { formData } = $props();

// this should not warn. it already signals intent
let initial = $state($state.snapshot(formData));
const dirty = $derived(!deepEqual(initial, formData));

On the case where you want it to update, like when navigating to the same form on another URL, then you can wrap the form with {#key page.url}{/key} or use an $effect.

$effect(() => {
  void page.url;
  initial = untrack(() => formData);
});

Another benefit of this is that passing deeply nested $state doesn't trigger unexpected updates to the initial value, whereas relying on the comment would cause that to happen.

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions