Contexts
Contexts provide an easy way to share data between components without drilling props through multiple levels of the component hierarchy.
Using contexts
It is a good habit to use the
new type idiom when describing
the type of the data to be passed. Imagine the simple use-case of creating a global dark mode state
for our website. We can define the following DarkMode
struct.
;
Providing contexts
To make a context value accessible, we need to use the provide_context_ref
method. Since we want
the context value to be reactive, we actually want a Signal<DarkMode>
to be provided.
let dark_mode = create_signal;
provide_context_ref;
You might notice that there are two different methods for providing context: provide_context
and
provide_context_ref
. The first one is for providing a value, whereas the later is for providing a
reference. The first one is simply a wrapper around create_ref
and provide_context_ref
. For
example, the two following code snippets are equivalent.
let value = 123;
let value_ref = create_ref;
provide_context_ref;
// or equivalently...
provide_context;
Using contexts.
Once the context has been provided, it can be used in any nested scope including from the same scope where the context value was provided.
To access the context, use the use_context
method.
let dark_mode = create_signal;
provide_context_ref;
view!
Remember that unlike contexts in React, the context is not reactive by itself. This is because
components only run once. In order to make a context value reactive, you need to use a Signal
or
other reactive data structure.