sycamore::reactive

Function create_signal

pub fn create_signal<T>(value: T) -> Signal<T>
Expand description

Create a new Signal.

Signals are reactive atoms, pieces of state that can be read and written to and which will automatically update anything which depend on them.

§Usage

The simplest way to use a signal is by using .get() and .set(...). However, this only works if the value implements Copy. If we wanted to store something that doesn’t implement Copy but implements Clone instead, say a String, we can use .get_clone() which will automatically clone the value for us.

let signal = create_signal(1);
signal.get(); // Should return 1.
signal.set(2);
signal.get(); // Should return 2.

There are many other ways of getting and setting signals, such as .with(...) and .update(...) which can access the signal even if it does not implement Clone or if you simply don’t want to pay the performance overhead of cloning your value everytime you read it.

§Reactivity

What makes signals so powerful, as opposed to some other wrapper type like RefCell is the automatic dependency tracking. This means that accessing a signal will automatically add it as a dependency in certain contexts (such as inside a create_memo) which allows us to update related state whenever the signal is changed.

let signal = create_signal(1);
// Note that we are accessing signal inside a closure in the line below. This will cause it to
// be automatically tracked and update our double value whenever signal is changed.
let double = create_memo(move || signal.get() * 2);
double.get(); // Should return 2.
signal.set(2);
double.get(); // Should return 4. Notice how this value was updated automatically when we
              // modified signal. This way, we can rest assured that all our state will be
              // consistent at all times!

§Ownership

Signals are always associated with a reactive node. This is what performs the memory management for the actual value of the signal. What is returned from this function is just a handle/reference to the signal allocted in the reactive node. This allows us to freely copy this handle around and use it in closures and event handlers without worrying about ownership of the signal.

This is why in the above example, we could access signal even after it was moved in to the closure of the create_memo.