Yew Framework

website·Indexed 35 days ago

https://yew.rs

A Rust framework for creating multi-threaded web applications with WebAssembly. Documentation covers function and struct components, the html! macro, routing for SPAs, state management, and advanced features like Suspense, Portals, and Agents for offloading tasks to web workers. Supports versions 0.21, 0.22, 0.23, and Next.

Tokens
143.5K
Snippets
673
Records
1K
Agent score
68%

What's inside Yew

  1. Overview of Yew Components

    Components are the fundamental building blocks of Yew applications. They are responsible for computing the HTML (DOM) visible to the user. Key characteristics include:

    • They accept arguments via Props.
    • They can maintain their own internal state.
    • They produce Html (which is an alias for VNode), representing a virtual version of the DOM.
  2. Overview of Yew Components

    Components are the primary building blocks of Yew applications. They are designed to encapsulate reusable pieces of UI, taking arguments via Props, maintaining their own internal state, and computing the HTML (DOM) visible to the user. Yew uses a Virtual DOM (VDOM) approach where it computes a virtual tree of components and reconciles changes to the actual DOM during rendering. In Yew, the Html type is an alias for VNode (a virtual node).
  3. Understand pure function components in Yew

    A Yew function component is considered pure when the returned Html is deterministically derived from its props. This means the view function does not mutate state or produce side effects; for any given set of props, it will always produce the same Html output.
    use yew::{Properties, component, Html, html};
    
    #[derive(Properties, PartialEq)]
    pub struct Props {
        pub is_loading: bool,
    }
    
    #[component]
    fn HelloWorld(props: &Props) -> Html {
        if props.is_loading {
            html! { "Loading" }
        } else {
            html! { "Hello world" }
        }
    }
  4. Avoid prop drilling using Yew Contexts

    Prop drilling occurs when data must be passed through multiple intermediate components to reach a deeply nested child. Yew Contexts solve this by allowing a parent component to make data available to any component in its subtree, regardless of depth, without explicitly passing props through every level.
  5. Use web-sys to access Web APIs in Rust

    The web-sys crate provides Rust bindings for Web APIs, enabling developers to interact with browser features (like the DOM) using a type-safe, 'rustified' interface instead of writing raw JavaScript.
    let document = window.document;
  6. Handle trailing slashes in routes

    Routes in yew-router are sensitive to trailing slashes; /about and /about/ are treated as distinct routes. This affects how browsers resolve relative asset paths. To support both, define separate enum variants for each version of the path.
    #[derive(Clone, Routable, PartialEq)]
    enum Route {
        #[at("/about")]
        About,
        #[at("/about/")]
        AboutSlash,
    }
  7. Offload tasks using Yew Agents

    Agents in Yew are used to offload tasks to web workers, allowing them to run concurrently. Because Public and Private agents utilize web workers, they incur serialization overhead for messages sent and received. Yew uses bincode for communication between threads, making this operation more expensive than a standard function call.
  8. Understand the purpose and behavior of the `html!` macro

    The html! macro converts a custom HTML-like declarative syntax into valid Rust code. While not strictly required for Yew development, it is recommended because it allows the UI layout code to closely match the generated HTML. The macro generates code that utilizes the public Yew library API (though some internal methods are undocumented to prevent misuse). To ensure hygiene and avoid name collisions, the macro uses fully qualified paths (e.g., ::yew::<module> and ::alloc::vec::Vec::new()) and explicit trait dispatch (e.g., <Type as Trait>).
  9. Use Component Scope to manage messages and callbacks

    In Yew, the Scope object is the primary mechanism for components to trigger updates and create callbacks. A reference to the component's scope is obtained by calling ctx.link() on the Context object passed to the component's lifecycle methods (such as create or view).
  10. Handle panics in Yew

    Yew automatically logs panics directly to the browser console, allowing developers to identify runtime crashes without additional configuration.
  11. Implement the Yew Component lifecycle

    The Component trait in Yew defines a set of lifecycle methods that manage a component's existence from creation to destruction. To create a struct component, you must implement the Component trait, specifying the Message and Properties associated types.
    impl Component for MyComponent {
        type Message = Msg;
        type Properties = Props;
    
        fn create(ctx: &Context<Self>) -> Self {
            MyComponent
        }
    
        fn view(&self, ctx: &Context<Self>) -> Html {
            html! { /* ... */ }
        }
    }
  12. Avoid prop drilling using Yew Contexts

    Prop drilling occurs when data must be passed through multiple intermediate components to reach a deeply nested child. Yew Contexts solve this by allowing a parent component to make data available to any component in its subtree, regardless of depth, without explicitly passing props through every level.