The docs for the context API have this example:
import { getContext, setContext } from 'svelte';let userKey = Symbol('user');export function setUserContext(user: User) { setContext(userKey, user);}export function getUserContext(): User { return getContext(userKey) as User;}
I suppose that the code above would live outside a component, e.g., into a svelte.js file.
Then I would import setUserContext
in some component (say <ComponentA>
) so that the context becomes available to that component and its whole subtree.
Then a child of <ComponentA>
can import getUserContext to access the context.
Now, my question is: why does setUserContext
take an argument?
Can I define it like this instead?
export function setUserContext() { setContext(userKey, user);}
So that I don't need to have the user in <ComponentA>
just to be able to call setUserContext
.
Also, bonus question, if the context was reactive (e.g., declared with a $state rune) nothing would change right?