Skip to content

mutating derived state also mutates the original state svelte 5 #15890

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Keshav-writes-code opened this issue May 10, 2025 · 1 comment
Closed

Comments

@Keshav-writes-code
Copy link

Describe the bug

Code

<script>
	let initial = $state([]);
	let mutable = $derived(initial);
	mutable.push({name: "something"})
	$inspect(initial)
</script>

Console

init 
(1) [ {…} ]
0: { name: "something" }
length: 1

but it shouldn't mutate the original initial state

Reproduction

Reproduction URL
Opoen this Svelte Playground link and open up the Playground's Console adn see the Intial State having the pushed item

Logs

System Info

System:
    OS: Linux 5.10 Debian GNU/Linux 12 (bookworm) 12 (bookworm)
    CPU: (12) x64 Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz
    Memory: 6.32 GB / 11.60 GB
    Shell: 5.9 - /usr/bin/zsh
  Binaries:
    Node: 22.15.0 - ~/.config/nvm/versions/node/v22.15.0/bin/node
    npm: 10.9.2 - ~/.config/nvm/versions/node/v22.15.0/bin/npm
    bun: 1.2.10 - ~/.bun/bin/bun

Severity

annoyance

@7nik
Copy link
Contributor

7nik commented May 10, 2025

It is so by design - you just return the original object.
You should think about that code like this:

let initial = []; // $state marks this variable and value as reactive
let mutable = initial; // $derived just re-assigns the value when dependecies change
mutable.push({name: "something"});
console.log(initial); // $inspect is kind of reactive console.log

If you want a copy - make a copy:

let shallowCopy = $derived([...original]);
let deepCopy = $derived($state.snapshot(original));

@Conduitry Conduitry closed this as not planned Won't fix, can't repro, duplicate, stale May 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants