Skip to content

How to direclty set a state as a Context? #13065

Answered by brunnerh
CarsonGH asked this question in Q&A
Discussion options

You must be logged in to vote

It's just about references and values in JS.

A property is a reference, accessing it gets the current value the property points to1.
If you have a variable that just contains a primitive like a number, passing that around does not transfer the variable, it transfers the value only.

So if you have...

let thing = $state(0);
setContext('thing', thing);

...you are only passing 0, the value of thing, not the variable/state itself. The signal is only triggered once when getting the value before setting the context.

If you do this instead...

let thing = $state(0);
setContext('thing', () => thing);

...you are passing a function that captures and references the state. Only calling the function the…

Replies: 1 comment 9 replies

Comment options

You must be logged in to vote
9 replies
@CarsonGH
Comment options

@brunnerh
Comment options

@CarsonGH
Comment options

@brunnerh
Comment options

Answer selected by CarsonGH
@CarsonGH
Comment options

@brunnerh
Comment options

@CarsonGH
Comment options

@brunnerh
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants