svelte: Docs and Tutorial do not match
Describe the bug
In https://svelte.dev/tutorial/svelte/context-api:
// in a parent component
import { setContext } from 'svelte';
let context = $state({...});
setContext('my-context', context);
// in a child component
import { getContext } from 'svelte';
const context = getContext('my-context');
But in https://svelte.dev/docs/svelte/compiler-warnings#state_referenced_locally you write:
let count = $state(0);
// warning: state_referenced_locally
setContext('count', count);
I the tutorial tells me to do so; but the compiler says: don’t?!
So what is right? Is there some kind of exception to setContext? Or is the tutorial wrong?
Reproduction
Just use the tutorial example.
Logs
System Info
System:
OS: Linux 6.14 Manjaro Linux
CPU: (16) x64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
Memory: 20.40 GB / 31.26 GB
Container: Yes
Shell: 4.0.2 - /usr/bin/fish
Binaries:
Node: 20.19.1 - /usr/bin/node
npm: 11.3.0 - /usr/bin/npm
bun: 1.2.1 - ~/.bun/bin/bun
Browsers:
Brave Browser: 136.1.78.97
Chromium: 136.0.7103.92
Severity
annoyance
About this issue
- Original URL
- State: closed
- Created a year ago
- Reactions: 1
- Comments: 16 (9 by maintainers)
Commits related to this issue
- fix: Automated changes for sveltejs/svelte#16004 by FixODev — committed to fixodev/svelte by deleted user a year ago
Because primitives cannot be mutated in JavaScript. Anything that looks like a mutation (e.g. count++) is in fact a reassignment.
This is by the way the same how JavaScript works by itself, if you don’t consider states:
With
$states, it works exactly the same way. You are working with the value of the state, it is not a wrapper object like e.g. vue has (where you need to refer to the value with .current)I don’t think the svelte docs are the place to explain how JavaScript works
The docs do mention that classes cannot be made deeply reactive with $state, but the properties must be declared with $state instead. SvelteMap and SvelteSet etc. do just that, for built-in JavaScript classes
To be more clear: The tutorial sets an object:
$state({...})The docs example uses a primitive:$state(0)Primitives are passed by value (copied), object are passed by reference, so their mutation has an effect.
The warning is technically correct…every assignment to
contextwill not propagate to the children but every mutation will…so it really depends on what you need to do but I agree we should probably document this better.