Crate leptos_reactive

source ·
Expand description

The reactive system for the Leptos Web framework.

§Fine-Grained Reactivity

Leptos is built on a fine-grained reactive system, which means that individual reactive values (“signals,” sometimes known as observables) trigger the code that reacts to them (“effects,” sometimes known as observers) to re-run. These two halves of the reactive system are inter-dependent. Without effects, signals can change within the reactive system but never be observed in a way that interacts with the outside world. Without signals, effects run once but never again, as there’s no observable value to subscribe to.

Here are the most commonly-used functions and types you’ll need to build a reactive system:

§Signals

  1. Signals: create_signal, which returns a (ReadSignal, WriteSignal tuple, or create_rw_signal, which returns a signal RwSignal without this read-write segregation.
  2. Derived Signals: any function that relies on another signal.
  3. Memos: create_memo, which returns a Memo.
  4. Resources: create_resource, which converts an async Future into a synchronous Resource signal.
  5. Triggers: create_trigger, creates a purely reactive Trigger primitive without any associated state.

§Effects

  1. Use create_effect when you need to synchronize the reactive system with something outside it (for example: logging to the console, writing to a file or local storage)
  2. The Leptos DOM renderer wraps any Fn in your template with create_effect, so components you write do not need explicit effects to synchronize with the DOM.

§Example

use leptos_reactive::*;

// creates a new reactive runtime
// this is omitted from most of the examples in the docs
// you usually won't need to call it yourself
let runtime = create_runtime();
// a signal: returns a (getter, setter) pair
let (count, set_count) = create_signal(0);

// calling the getter gets the value
// can be `count()` on nightly
assert_eq!(count.get(), 0);
// calling the setter sets the value
// can be `set_count(1)` on nightly
set_count.set(1);
// or we can mutate it in place with update()
set_count.update(|n| *n += 1);

// a derived signal: a plain closure that relies on the signal
// the closure will run whenever we *access* double_count()
let double_count = move || count.get() * 2;
assert_eq!(double_count(), 4);

// a memo: subscribes to the signal
// the closure will run only when count changes
let memoized_triple_count = create_memo(move |_| count.get() * 3);
// can be `memoized_triple_count()` on nightly
assert_eq!(memoized_triple_count.get(), 6);

// this effect will run whenever `count` changes
create_effect(move |_| {
    println!("Count = {}", count.get());
});

// disposes of the reactive runtime
runtime.dispose();

Re-exports§

Modules§

  • Callbacks define a standard way to store functions and closures. They are useful for component properties, because they can be used to define optional callback functions, which generic props don’t support.
  • This prelude imports all signal types as well as all signal traits needed to use those types.
  • This prelude imports all signal types as well as all signal traits needed to use those types.
  • Types that handle asynchronous data loading via <Suspense/>.

Macros§

Structs§

  • Handle to dispose of a reactive node.
  • A handle to an effect, can be used to explicitly dispose of the effect.
  • Represents its pending <Suspense/> fragment.
  • A wrapping type for an optional component prop, which can either be a signal or a non-reactive value, and which may or may not have a value. In other words, this is an Option<MaybeSignal<Option<T>>> that automatically flattens its getters.
  • An efficient derived reactive value based on other reactive values.
  • A reactive owner.
  • The getter for a reactive signal.
  • A signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Unique ID assigned to a Resource.
  • Unique ID assigned to a Runtime.
  • A signal that combines the getter and setter into one value, rather than separating them into a ReadSignal and a WriteSignal. You may prefer this its style, or it may be easier to pass around in a context or as a function argument.
  • Allows running a future that has access to a given scope.
  • A conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
  • A wrapper for any kind of readable reactive signal: a ReadSignal, Memo, RwSignal, or derived signal closure.
  • A wrapper for any kind of settable reactive signal: a WriteSignal, RwSignal, or closure that receives a value and sets a signal depending on it.
  • A non-reactive wrapper for any value, which can be created with store_value.
  • Describes a value that is either a static or a reactive string, i.e., a String, a &str, or a reactive Fn() -> String.
  • Reactive Trigger, notifies reactive code to rerun.
  • The setter for a reactive signal.

Enums§

  • Error returned from Oco::try_from for unsuccessful conversion from Oco<'_, [u8]> to Oco<'_, str>.
  • A wrapper for a value that is either T or Signal<T>.
  • “Owned Clones Once”: a smart pointer that can be either a reference, an owned value, or a reference-counted pointer. This is useful for storing immutable values, such as strings, in a way that is cheap to clone and pass around.
  • Describes errors that can occur while serializing and deserializing data, typically during the process of streaming Resources from the server to the client.

Traits§

  • Helper trait for converting Fn() -> T closures into Signal<T>.
  • Helper trait for converting Fn(T) into SignalSetter<T>.
  • Describes an object that can be serialized to or from a supported format Currently those are JSON and Cbor
  • This trait allows disposing a signal before its owner has been disposed.
  • This trait allows getting an owned value of the signals inner type.
  • Trait implemented for all signal types which you can get a value from, such as ReadSignal, Memo, etc., which allows getting the inner value without subscribing to the current scope.
  • This trait allows setting the value of a signal.
  • Trait implemented for all signal types which you can set the inner value, such as WriteSignal and RwSignal, which allows setting the inner value without causing effects which depend on the signal from being run.
  • This trait allows converting a signal into a async Stream.
  • This trait allows updating the inner value of a signal.
  • This trait allows updating the signals value without causing dependant effects to run.
  • This trait allows obtaining an immutable reference to the signal’s inner type.
  • This trait allows getting a reference to the signals inner value without creating a dependency on the signal.

Functions§

  • Wraps the given function so that, whenever it is called, it creates a child node owned by whichever reactive node was the owner when it was created, runs the function, and returns a disposer that can be used to dispose of the child later.
  • Batches any reactive updates, preventing effects from running until the whole function has run. This allows you to prevent rerunning effects if multiple signal updates might cause the same effect to run.
  • Creates a “blocking” Resource. When server-side rendering is used, this resource will cause any <Suspense/> you read it under to block the initial chunk of HTML from being sent to the client. This means that if you set things like HTTP headers or <head> metadata in that <Suspense/>, that header material will be included in the server’s original response.
  • Effects run a certain chunk of code whenever the signals they depend on change. create_effect queues the given function to run once, tracks its dependence on any signal values read within it, and reruns the function whenever the value of a dependency changes.
  • Creates an effect; unlike effects created by create_effect, isomorphic effects will run on the server as well as the client.
  • Creates a local Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Creates a local Resource with the given initial value, which will only generate and run a Future using the fetcher when the source changes.
  • Creates an efficient derived reactive value based on other reactive values.
  • Like create_memo, create_owning_memo creates an efficient derived reactive value based on other reactive values, but with two differences:
  • Takes a memoized, read-only slice of a signal. This is equivalent to the read-only half of create_slice.
  • Creates an effect exactly like create_effect, but runs immediately rather than being queued until the end of the current microtask. This is mostly used inside the renderer but is available for use cases in which scheduling the effect for the next tick is not optimal.
  • Creates a Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Creates a Resource with the given initial value, which will only generate and run a Future using the fetcher when the source changes.
  • Creates a new reactive runtime and sets it as the current runtime.
  • Creates a reactive signal with the getter and setter unified in one value. You may prefer this style, or it may be easier to pass around in a context or as a function argument.
  • Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether it is equal to the key value (as determined by PartialEq.)
  • Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
  • Creates a signal, the basic reactive primitive.
  • Creates a signal that always contains the most recent value emitted by a Stream. If the stream has not yet emitted a value since the signal was created, the signal’s value will be None.
  • Derives a reactive slice of an RwSignal.
  • Creates a Trigger, a kind of reactive primitive.
  • Creates a setter to access one slice of a signal. This is equivalent to the write-only half of create_slice.
  • The current reactive runtime.
  • Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context.
  • Creates a cleanup function, which will be run when the current reactive owner is disposed.
  • Provides a context value of type T to the current reactive node and all of its descendants. This can be consumed using use_context.
  • The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser’s event loop.
  • Runs the given function as a child of the current Owner, once.
  • Sets the current reactive runtime.
  • Spawns and runs a thread-local Future in a platform-independent way.
  • Runs a future that has access to the provided Owner’s scope context.
  • Runs a future that has access to the provided Owner’s scope context.
  • Creates a non-reactive wrapper for any value by storing it within the reactive system.
  • Attempts to batch any reactive updates, preventing effects from running until the whole function has run. This allows you to prevent rerunning effects if multiple signal updates might cause the same effect to run.
  • Runs a future that has access to the provided Owner’s scope context.
  • Runs a future that has access to the provided Owner’s scope context.
  • Runs the given code with the given reactive owner.
  • Suspends reactive tracking while running the given function.
  • Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context.
  • A version of create_effect that listens to any dependency that is accessed inside deps and returns a stop handler.
  • Wraps the given function so that, whenever it is called, it is run in the reactive scope of whatever the reactive owner was when it was created.
  • Runs the given code with the given reactive owner.