Yew: Components, Props & the html! Macro
Yew is a modern Rust framework for building client-side web applications, using a component-based architecture similar in spirit to React. Rust code compiles to WebAssembly, which runs in the browser at near-native speed -- browsers only natively understand JavaScript, so Wasm bridges that gap.
A Basic Function Component
use yew::prelude::*;
#[function_component]
fn App() -> Html {
let counter = use_state(|| 0);
// Rust's ownership rules require explicit cloning before moving
// a value into a closure -- unlike JavaScript's garbage collector
let onclick = {
let counter = counter.clone();
Callback::from(move |_| counter.set(*counter + 1))
};
// html! macro: JSX-like syntax processed at compile time into
// the Rust code needed to construct this UI structure
html! {
<div>
<p>{ format!("Count: {}", *counter) }</p>
<button {onclick}>{ "Increment" }</button>
</div>
}
}Props: Strongly-Typed Data from Parent to Child
#[derive(Properties, PartialEq)]
struct GreetingProps {
name: String,
}
#[function_component]
fn Greeting(props: &GreetingProps) -> Html {
html! { <p>{ format!("Hello, {}!", props.name) }</p> }
}
// Usage -- Rust catches prop-shape mismatches at COMPILE time,
// a meaningful advantage over plain JavaScript React
html! { <Greeting name="Alice" /> }Message-Based State (Class Components)
// Inspired by The Elm Architecture -- explicit messages trigger
// well-defined state transitions, similar to Redux's action/reducer
enum Msg {
Increment,
Decrement,
}
impl Component for Counter {
type Message = Msg;
type Properties = ();
fn update(&mut self, _ctx: &Context<Self>, msg: Msg) -> bool {
match msg {
Msg::Increment => self.value += 1,
Msg::Decrement => self.value -= 1,
}
true // re-render
}
}Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free