Expand description
About Leptos
Leptos is a full-stack framework for building web applications in Rust. You can use it to build
- single-page apps (SPAs) rendered entirely in the browser, using client-side routing and loading or mutating data via async requests to the server
- multi-page apps (MPAs) rendered on the server, managing navigation, data, and mutations via
web-standard
<a>and<form>tags - progressively-enhanced single-page apps that are rendered on the server and then hydrated on the client,
enhancing your
<a>and<form>navigations and mutations seamlessly when WASM is available.
And you can do all three of these using the same Leptos code.
nightly Note
Most of the examples assume you’re using nightly Rust. If you’re on stable, note the following:
- You need to enable the
"stable"flag inCargo.toml:leptos = { version = "0.0", features = ["stable"] } nightlyenables the function call syntax for accessing and setting signals. If you’re usingstable, you’ll just call.get(),.set(), or.update()manually. Check out thecounters_stableexample for examples of the correct API.
Learning by Example
If you want to see what Leptos is capable of, check out the examples:
counteris the classic counter example, showing the basics of client-side rendering and reactive DOM updatescounter_without_macrosadapts the counter example to use the builder pattern for the UI and avoids other macros, instead showing the code that Leptos generates.countersintroduces parent-child communication via contexts, and the<For/>component for efficient keyed list updates.counters_stableadapts thecountersexample to show how to use Leptos withstableRust.error_boundaryshows how to useResulttypes to handle errors.parent_childshows four different ways a parent component can communicate with a child, including passing a closure, context, and morefetchintroduces Resources, which allow you to integrate arbitraryasynccode like an HTTP request within your reactive code.routershows how to use Leptos’s nested router to enable client-side navigation and route-specific, reactive data loading.counter_isomorphicshows different methods of interaction with a stateful server, including server functions, server actions, forms, and server-sent events (SSE).todomvcshows the basics of building an isomorphic web app. Both the server and the client import the same app code from thetodomvcexample. The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive. You might also want to see how we use create_effect to serialize JSON tolocalStorageand reactively call DOM methods on references to elements.hackernewsandhackernews_axumintegrate calls to a real external REST API, routing, server-side rendering and hydration to create a fully-functional application that works as intended even before WASM has loaded and begun to run.todo_app_sqlite,todo_app_sqlite_axum, andtodo_app_sqlite_vizshow how to build a full-stack app using server functions and database connections.tailwindshows how to integrate TailwindCSS withcargo-leptos.
Details on how to run each example can be found in its README.
Quick Links
Here are links to the most important sections of the docs:
- Reactivity: the leptos_reactive overview, and more details in
- signals: create_signal, ReadSignal, and WriteSignal (and create_rw_signal and RwSignal)
- computations: create_memo and Memo
asyncinterop: create_resource and Resource for loading data usingasyncfunctions, and create_action and Action to mutate data or imperatively callasyncfunctions.- reactions: create_effect
- Templating/Views: the view macro
- Routing: the leptos_router crate
- Server Functions: the server macro, create_action, and create_server_action
Feature Flags
csr(Default) Client-side rendering: Generate DOM nodes in the browserssrServer-side rendering: Generate an HTML string (typically on the server)hydrateHydration: use this to add interactivity to an SSRed Leptos appstableBy default, Leptos requiresnightlyRust, which is what allows the ergonomics of calling signals as functions. If you need to usestable, you will need to call.get()and.set()manually.serde(Default) In SSR/hydrate mode, uses serde to serialize resources and send them from the server to the client.serde-liteIn SSR/hydrate mode, uses serde-lite to serialize resources and send them from the server to the client.miniserdeIn SSR/hydrate mode, uses miniserde to serialize resources and send them from the server to the client.
Important Note: You must enable one of csr, hydrate, or ssr to tell Leptos
which mode your app is operating in.
A Simple Counter
use leptos::*;
#[component]
pub fn SimpleCounter(cx: Scope, initial_value: i32) -> impl IntoView {
// create a reactive signal with the initial value
let (value, set_value) = create_signal(cx, initial_value);
// create event handlers for our buttons
// note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures
let clear = move |_| set_value.set(0);
let decrement = move |_| set_value.update(|value| *value -= 1);
let increment = move |_| set_value.update(|value| *value += 1);
// this JSX is compiled to an HTML template string for performance
view! {
cx,
<div>
<button on:click=clear>"Clear"</button>
<button on:click=decrement>"-1"</button>
<span>"Value: " {move || value().to_string()} "!"</span>
<button on:click=increment>"+1"</button>
</div>
}
}Leptos is easy to use with Trunk (or with a simple wasm-bindgen setup):
#[component]
fn SimpleCounter(cx: Scope, initial_value: i32) -> impl IntoView {
todo!()
}
pub fn main() {
mount_to_body(|cx| view! { cx, <SimpleCounter initial_value=3 /> })
}Re-exports
pub use leptos_config;pub use leptos_dom;pub use leptos_server;pub use server_fn;pub use server_fn::ServerFn as _;pub use typed_builder;
Modules
- Types for all DOM events.
- Exports types for working with HTML elements.
- Exports types for working with MathML elements.
- This prelude imports all signal types as well as all signal traits needed to use those types.
- Utilities for server-side rendering HTML.
- Exports types for working with SVG elements.
Macros
- Uses
println!()-style formatting to log warnings to the console (in the browser) or viaeprintln!()(if not in the browser), but only if it’s a debug build. - Uses
println!()-style formatting to log errors to the console (in the browser) or viaeprintln!()(if not in the browser). - Uses
println!()-style formatting to log something to the console (in the browser) or viaprintln!()(if not in the browser). - An optimized, cached template for client-side rendering. Follows the same syntax as the view! macro. In hydration or server-side rendering mode, behaves exactly as the
viewmacro. In client-side rendering mode, uses a<template>node to efficiently render the element. Should only be used with a single root element. - The
viewmacro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences: - Uses
println!()-style formatting to log warnings to the console (in the browser) or viaeprintln!()(if not in the browser).
Structs
- An action synchronizes an imperative
asynccall to the synchronous reactive system. - Props for the
ErrorBoundarycomponent. - Builder for
ErrorBoundaryPropsinstances. - A struct to hold all the possible errors that could be provided by child Views
- Props for the
Forcomponent. - Builder for
ForPropsinstances. - Represents a group of
views. - Represents an HTML element.
- This struct serves as a convenient place to store details used for configuring Leptos. It’s used in our actix, axum, and viz integrations to generate the correct path for WASM, JS, and Websockets, as well as other configuration tasks. It shares keys with cargo-leptos, to allow for easy interoperability
- An efficient derived reactive value based on other reactive values.
- An action that synchronizes multiple imperative
asynccalls to the reactive system, tracking the progress of each one. - Contains a shared reference to a DOM node created while using the
viewmacro to create your UI. - The getter for a reactive signal.
- A signal that reflects the current state of an asynchronous task, allowing you to integrate
asyncFutures 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.
- A Each scope can have child scopes, and may in turn have a parent.
- Creating a Scope gives you a disposer, which can be called to dispose of that reactive scope.
- Unique ID assigned to a Scope.
- Props for the
Showcomponent. - Builder for
ShowPropsinstances. - 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.
- Props for the
Suspensecomponent. - Builder for
SuspensePropsinstances. - Props for the
Transitioncomponent. - Builder for
TransitionPropsinstances. - The setter for a reactive signal.
Enums
- Represents the different possible values an attribute node could have.
- Represents the different possible values a single class on an element could have, allowing you to do fine-grained updates to single items in
Element.classList. - A wrapper for a value that is either
TorSignal<T>. - Represents the different possible values an element property could have, allowing you to do fine-grained updates to single fields.
- Describes errors that can occur while serializing and deserializing data, typically during the process of streaming Resources from the server to the client.
- Type for errors that can occur when using server functions.
- A leptos view which can be mounted to the DOM.
Traits
- Converts some type into an Attribute.
- Converts some type into a Class.
- Converts some type into a Property.
- Helper trait for converting
Fn() -> Tclosures intoSignal<T>. - Helper trait for converting
Fn(T)intoSignalSetter<T>. - Converts the value into a
View. - Describes an object that can be serialized to or from a supported format Currently those are JSON and Cbor
- Defines a “server function.” A server function can be called from the server or the client, but the body of its code will only be run on the server, i.e., if a crate feature
ssris enabled. - This trait allows disposing a signal before its Scope has been disposed.
- This trait allows getting an owned value of the signals inner type.
- Trait implemented for all signal types which you can
geta value from, such asReadSignal,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
setthe inner value, such asWriteSignalandRwSignal, 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
- When you render a
Result<_, _>in your view, in theErrcase it will render nothing, and search up through the view tree for an<ErrorBoundary/>. This component lets you define a fallback that should be rendered in that error case, allowing you to handle errors within a section of the interface. - Iterates over children and displays them, keyed by the
keyfunction given. - A component that will show its children when the
whencondition istrue, and show the fallback when it isfalse, without rerendering every time the condition changes. - If any Resources are read in the
childrenof this component, it will show thefallbackwhile they are loading. Once all are resolved, it will render thechildren. - Creates an Action to synchronize an imperative
asynccall to the synchronous reactive system. - Effects run a certain chunk of code whenever the signals they depend on change.
create_effectimmediately runs the given function 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.
- Works exactly as create_signal, but creates multiple signals at once.
- Works exactly as create_many_signals, but applies the map function to each signal pair.
- Creates an efficient derived reactive value based on other reactive values.
- Creates an MultiAction to synchronize an imperative
asynccall to the synchronous reactive system. - Creates a shared reference to a DOM node created while using the
viewmacro to create your UI. - 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 an Action that can be used to call a server function.
- Creates an MultiAction that can be used to call a server function.
- 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.
- Returns the
Document. - Helper function to extract
Event.targetfrom any event. - Helper function to extract
event.target.checkedfrom an event. - Helper function to extract
event.target.valuefrom an event. - Loads LeptosOptions from a Cargo.toml with layered overrides. If an env var is specified, like
LEPTOS_ENV, it will override a setting in the file. It takes in an optional path to a Cargo.toml file. If None is provided, you’ll need to set the options as environment variables or rely on the defaults. This is the preferred approach for cargo-leptos. If Some(“./Cargo.toml”) is provided, Leptos will read in the settings itself. This option currently does not allow dashes in file or folder names, as all dashes become underscores - Runs the provided closure and mounts the result to the provided element.
- Runs the provided closure and mounts the result to the
<body>. - Creates a cleanup function, which will be run when a Scope is disposed.
- Provides a context value of type
Tto the current reactive Scope and all of its descendants. This can be consumed using use_context. - Exposes the queueMicrotask method in the browser, and simply runs the given function when on the server.
- Runs the given function between the next repaint using
Window.requestAnimationFrame. - Runs the given function between the next repaint using
Window.requestAnimationFrame, returning a cancelable handle. - Queues the given function during an idle period using
Window.requestIdleCallback. - Queues the given function during an idle period using
Window.requestIdleCallback, returning a cancelable handle. - set_intervalDeprecatedRepeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See
setInterval(). - Repeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See
setInterval(). - Executes the given function after the given duration of time has passed.
setTimeout(). - Executes the given function after the given duration of time has passed, returning a cancelable handle.
setTimeout(). - Spawns and runs a thread-local std::future::Future in a platform-independent way.
- Creates a non-reactive wrapper for any value by storing it within the reactive system.
- Extracts a context value of type
Tfrom the reactive system by traversing it upwards, beginning from the current Scope and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context. - Returns the
Window. - Adds an event listener to the
Window.
Type Definitions
- A type for taking anything that implements
IntoAttribute. - The most common type for the
childrenproperty on components, which can only be called once. - A type for the
childrenproperty on components that can be called more than once. - A type for the
childrenproperty on components that can be called more than once, but may mutate the children.
Attribute Macros
- Annotates a function so that it can be used with your template as a Leptos
<Component/>. - Declares that a function is a server function. This means that its body will only run on the server, i.e., when the
ssrfeature is enabled.
Derive Macros
- Derives a trait that parses a map of string keys and values into a typed data structure, e.g., for route params.