Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Yew

Learn Yew - 9 Code Examples & CST Typing Practice Test

Yew is a modern Rust framework for building client-side web applications using WebAssembly (Wasm), providing a reactive component-based architecture similar to React.

View all 9 Yew code examples →
Simple Yew ComponentYew Component with Button ClickYew Component with Input BindingYew Component with Conditional RenderingYew Component with LoopYew Component with Child ComponentYew Component with TimerYew Component with FormYew Component with Conditional and Loop Combined

Learn YEW with Real Code Examples

Updated Nov 25, 2025

Explain

Yew allows developers to write web frontends in Rust, compiling to WebAssembly for high-performance execution in browsers.

It supports a component-based model with properties, messages, and lifecycle hooks.

Includes a virtual DOM for efficient UI updates and re-rendering.

Integrates with web APIs such as fetch, WebSockets, and local storage.

Ideal for building fast, type-safe web applications without relying on JavaScript.

Core Features

HTML-like macro syntax for building UI (`html!`) in Rust

Message-based component communication

Properties (props) for component configuration

Lifecycle hooks (create, update, change, destroy)

Integration with browser APIs and JS interop

Basic Concepts Overview

Component - reusable UI unit

Message - triggers updates inside components

Props - component input properties

Virtual DOM - efficient UI rendering

Lifecycle hooks - component creation, update, and destruction

Project Structure

src/ - main Rust source code

Cargo.toml - project dependencies and metadata

index.html - root HTML page

static/ - static assets (images, CSS)

tests/ - unit and integration tests

Building Workflow

Write Rust code using `html!` macro for UI

Define components with messages and props

Use message passing to handle events and state updates

Build project to WebAssembly using `trunk` or `wasm-pack`

Serve app via local server and test in browser

Difficulty Use Cases

Beginner: simple interactive component

Intermediate: SPA with routing and state management

Advanced: complex dashboard with async data fetching

Expert: WebAssembly game or graphics-heavy app

Auditor: optimize performance and memory usage in Wasm

Comparisons

Yew vs React: Rust/Wasm vs JavaScript, stronger type safety and performance

Yew vs Svelte: Component-based UI, but compiled to Wasm vs JS

Yew vs Angular: Yew is Rust-focused, Angular is full-featured JS framework

Yew vs Seed: Both Rust/Wasm frameworks, Yew has larger ecosystem

Yew vs Vanilla JS: Type-safe Rust with virtual DOM vs JS direct DOM manipulation

Versioning Timeline

2018 - Yew initial release

2019 - Virtual DOM and component lifecycle stabilization

2020 - async support and wasm-pack integration

2021 - Yew Router and expanded ecosystem

2022-2025 - Performance improvements, new macros, larger community adoption

Glossary

Component - reusable UI element

Message - triggers state update

Props - input parameters to components

Virtual DOM - optimized UI diffing

Wasm - WebAssembly compiled output from Rust

Installation Setup

Install Rust and Cargo package manager

Install `wasm-pack` for WebAssembly builds

Create a new Rust project for Yew

Add `yew` crate and optional dependencies (`wasm-bindgen`, `web-sys`)

Build project using `wasm-pack build` or `trunk` for development server

Environment Setup

Install Rust and Cargo

Install wasm-pack and Trunk

Set up browser for testing (modern browsers)

Install Yew crate and dependencies

Run development server and compile to Wasm

Config Files

Cargo.toml - dependencies and project metadata

index.html - root HTML page

src/main.rs - entry point

src/components/ - reusable components

static/ - CSS and assets

Cli Commands

cargo new project_name -> create new Rust project

cargo build --target wasm32-unknown-unknown -> compile to Wasm

trunk serve -> start local dev server

trunk build -> build for production

wasm-bindgen -> generate JS bindings

Internationalization

UTF-8 support by default

Localized strings handled in Rust code

Integrate i18n libraries manually

Dynamic content can be localized

Flexible for multi-language apps

Accessibility

Supports standard HTML accessibility

Custom ARIA attributes via html! macro

Keyboard and mouse events supported

Screen reader-friendly rendering

No native accessibility utilities; use standard web practices

Ui Styling

CSS and static assets handled separately

Inline styling possible via style attributes

Integrate frameworks like Tailwind CSS

No built-in CSS framework

Dynamic class updates via props or state

State Management

Component-local state via use_state hook

Message passing for state updates

Props to pass data between components

Async data handled with wasm-bindgen-futures

Global state via context or external crates

Data Management

Handle JSON, HTML, or binary data

Fetch API for network requests

Use local storage or IndexedDB

Manage async responses in messages

Interoperate with backend services

Architecture

Component-based architecture similar to React

Virtual DOM for efficient diffing and rendering

Message-based update system for reactivity

Rust compiled to WebAssembly running in the browser

Supports asynchronous operations with `wasm-bindgen-futures`

Rendering Model

html! macro -> Virtual DOM node

Diffing algorithm detects changes

Updates only necessary DOM elements

Reactivity via message passing

Efficient rendering in WebAssembly

Architectural Patterns

Component-as-a-Service for UI

Message-driven state updates

Asynchronous fetch handling

Virtual DOM diffing

Integration with browser APIs

Real World Architectures

Single-page applications with Rust backend

Data visualization dashboards

Interactive educational apps

WebAssembly games

Realtime chat or collaboration tools

Design Principles

Component-based architecture

Virtual DOM for efficient rendering

Message-driven reactivity

Memory safety via Rust

Compile-to-Wasm for browser performance

Scalability Guide

Efficient UI updates via virtual DOM

Async operations handled via futures

Component-based design for modularity

Code splitting possible with multiple Wasm modules

Optimize Wasm binary size for faster load

Migration Guide

Adapt JS/React projects to Yew by rewriting components in Rust

Use wasm-bindgen for JS interop

Replace JS async with Rust futures

Use virtual DOM and messages for reactivity

Test WebAssembly output in target browsers

Performance Notes

High-performance execution due to WebAssembly

Startup overhead may occur on first load

Virtual DOM reduces unnecessary DOM operations

Memory safety prevents common bugs and leaks

Async tasks run efficiently with Rust's futures

Security Notes

Memory safety guarantees via Rust

Compile-time checks prevent undefined behavior

Wasm sandbox restricts unsafe access to browser environment

Use HTTPS for network requests

Validate user input for frontend logic

Monitoring Analytics

Browser DevTools for performance profiling

Network tab to monitor fetch requests

Memory tab to detect leaks

Use logging via console_log crate

Analyze Wasm compilation and bundle size

Code Quality

Follow Rust best practices

Keep components modular and reusable

Use type-safe messages and props

Unit test components with Rust test framework

Optimize Wasm size and performance

Practical Examples

Todo list SPA in Rust/Wasm

Interactive charting dashboard with async data fetch

WebAssembly game with user input handling

CRUD frontend for a Rust backend service

WebSocket-based realtime chat application

Troubleshooting

Ensure Rust toolchain and wasm-pack/trunk are installed

Check browser console for runtime errors

Verify proper async/await usage with wasm-bindgen-futures

Inspect component message flows and state updates

Ensure all dependencies are correctly declared in Cargo.toml

Testing Guide

Unit test components with Rust testing framework

Integration tests for async interactions

Use `wasm-bindgen-test` for Wasm-specific tests

Browser-based testing with headless browsers

Check component reactivity and state changes

Deployment Options

Compile to Wasm and host on static server

Use Trunk to bundle Wasm, JS glue, and static assets

Deploy via Netlify, Vercel, or any static hosting

Integrate with existing Rust backend APIs

Serve SPA through CDN for fast global access

Tools Ecosystem

Rust and Cargo

wasm-pack for WebAssembly builds

Trunk for development and bundling

web-sys and js-sys for JS interop

Yew component crates and libraries

Integrations

Fetch API for HTTP requests

WebSocket and WebRTC for realtime communication

Local storage and IndexedDB via web-sys

Integration with JS libraries via wasm-bindgen

Yew Router for SPA navigation

Productivity Tips

Use component modularity to simplify maintenance

Leverage Rust compiler for early bug detection

Optimize virtual DOM updates

Use wasm-bindgen efficiently for JS interop

Minimize Wasm bundle size for faster load

Challenges

Rust compiler and Wasm toolchain setup

Debugging WebAssembly in browsers

Long compile times for large apps

Interoperating with existing JavaScript libraries

Managing complex component state efficiently

Learning Path

Learn Rust basics

Understand WebAssembly concepts

Install wasm-pack and Trunk

Build simple Yew components and SPAs

Integrate async fetch and browser APIs

Skill Improvement Plan

Week 1: Rust fundamentals and ownership model

Week 2: WebAssembly basics and compiling Rust to Wasm

Week 3: Build basic Yew components

Week 4: Handle async requests and complex state

Week 5: Optimize performance and memory usage in Wasm

Interview Questions

What is Yew and how does it work?

Explain the component lifecycle in Yew

How does Yew compare with React or Svelte?

Describe message passing and reactive updates

How do you handle asynchronous data fetching in Yew?

Cheat Sheet

html! { } -> Render HTML template in component

Component struct -> define UI logic and state

Msg enum -> define messages for component updates

Link<Msg> -> send messages to component

use_effect / use_state -> hooks for state and effects

Books

Yew in Action

Rust and WebAssembly for Web Developers

Building SPAs with Rust and Yew

Mastering Rust WebAssembly

High-Performance Web Apps with Yew

Tutorials

Getting started with Yew and Rust

Building a SPA with Yew

Handling async data with wasm-bindgen-futures

Using components and props effectively

Deploying Yew WebAssembly apps

Official Docs

https://yew.rs/docs/

https://docs.rs/yew/

Community Links

Yew GitHub repository

Yew Discord server

Reddit r/rust

Rust Users Forum

Crates.io Yew page

Community Support

Yew GitHub repository

Yew Discord server

Reddit r/rust and r/WebAssembly

Rust community forums

Crates.io for Yew-related crates

Monetization

High-performance frontend for SaaS apps

WebAssembly games or interactive content

Dashboards for analytics platforms

Browser-based tools with Rust safety

Web apps with low-latency and memory efficiency

Future Roadmap

Improved developer tooling and macros

Better interop with JavaScript ecosystem

Smaller Wasm bundle sizes

Expanded ecosystem and component libraries

Enhanced debugging and profiling tools

When Not To Use

Simple static websites (overkill for small apps)

Projects heavily dependent on JS ecosystem libraries

Tiny apps where Rust toolchain setup is too heavy

Applications requiring server-side rendering out-of-the-box

Rapid prototyping where JS frameworks are faster

Final Summary

Yew is a Rust framework for building web apps with WebAssembly.

It offers component-based reactive programming with virtual DOM.

High performance, memory safety, and Rust type system benefits.

Integrates with browser APIs and supports async operations.

Ideal for Rust developers building SPAs, dashboards, or high-performance web apps.

Faq

Can Yew replace JavaScript frameworks?

Yes, for Rust developers, especially for performance-critical apps.

Do I need Rust knowledge to use Yew?

Yes - Rust basics are required.

Can Yew work with existing JS libraries?

Yes - via wasm-bindgen interop.

Does Yew support routing?

Yes - using Yew Router crate.

Is Yew production-ready?

Yes - used in many Rust/Wasm production projects.

Code Sample Descriptions

1

Simple Yew Component

# yew/demo/main.rs
use yew::prelude::*;

struct Model;

impl Component for Model {
    type Message = ();
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <h1>{"Hello, Yew!"}</h1>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

A basic Yew component displaying 'Hello, Yew!' in the browser.

Let’s Try →
2

Yew Component with Button Click

# yew/demo/button.rs
use yew::prelude::*;

struct Model {
    message: String,
}

enum Msg {
    Click,
}

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model { message: "Click the button!".into() }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
        Msg::Click => {
        self.message = "Button clicked!".into();
        true
        }
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <div>
        <p>{ &self.message }</p>
        <button onclick={ctx.link().callback(|_| Msg::Click)}>{"Click Me"}</button>
        </div>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

A component that updates a message when a button is clicked.

Let’s Try →
3

Yew Component with Input Binding

# yew/demo/input.rs
use yew::prelude::*;

struct Model {
    name: String,
}

enum Msg {
    Update(String),
}

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model { name: "".into() }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
        Msg::Update(val) => {
        self.name = val;
        true
        }
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <div>
        <input value={self.name.clone()} oninput={ctx.link().callback(|e: InputEvent| Msg::Update(e.data().unwrap_or_default()))} />
        <p>{ format!("Hello, {}!", self.name) }</p>
        </div>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

A component that binds input text to state.

Let’s Try →
4

Yew Component with Conditional Rendering

# yew/demo/conditional.rs
use yew::prelude::*;

struct Model {
    is_logged_in: bool,
}

enum Msg {
    Toggle,
}

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model { is_logged_in: false }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
        Msg::Toggle => {
        self.is_logged_in = !self.is_logged_in;
        true
        }
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <div>
        { if self.is_logged_in { html!{<p>{"Welcome back!"}</p>} } else { html!{<p>{"Please log in."}</p>} } }
        <button onclick={ctx.link().callback(|_| Msg::Toggle)}>{"Toggle"}</button>
        </div>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

Shows different content based on a boolean state.

Let’s Try →
5

Yew Component with Loop

# yew/demo/loop.rs
use yew::prelude::*;

struct Model {
    items: Vec<String>,
}

impl Component for Model {
    type Message = ();
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model { items: vec!["Item 1".into(), "Item 2".into(), "Item 3".into()] }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <ul>
        { for self.items.iter().map(|item| html!{<li>{ item }</li>}) }
        </ul>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

Displays a list of items using a loop.

Let’s Try →
6

Yew Component with Child Component

# yew/demo/child.rs
use yew::prelude::*;

#[derive(Properties, PartialEq)]
struct ChildProps {
    text: String,
}

#[function_component(ChildComponent)]
fn child(props: &ChildProps) -> Html {
    html! { <p>{ &props.text }</p> }
}

#[function_component(ParentComponent)]
fn parent() -> Html {
    html! { <ChildComponent text="Hello from Child" /> }
}

fn main() {
    yew::start_app::<ParentComponent>();
}

Demonstrates parent and child components.

Let’s Try →
7

Yew Component with Timer

# yew/demo/timer.rs
use yew::prelude::*;
use gloo_timers::callback::Interval;

struct Model {
    current_time: String,
}

impl Component for Model {
    type Message = (); 
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        let model = Model { current_time: "".into() };
        let link = ctx.link().clone();
        Interval::new(1000, move || link.send_message(())).forget();
        model
    }

    fn update(&mut self, ctx: &Context<Self>, _msg: Self::Message) -> bool {
        self.current_time = js_sys::Date::new_0().to_locale_time_string("en-US");
        true
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! { <p>{ &self.current_time }</p> }
    }
}

fn main() {
    yew::start_app::<Model>();
}

Updates state every second using IntervalService.

Let’s Try →
8

Yew Component with Form

# yew/demo/form.rs
use yew::prelude::*;

struct Model {
    name: String,
    message: String,
}

enum Msg {
    Update(String),
    Submit,
}

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model { name: "".into(), message: "".into() }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
        Msg::Update(val) => { self.name = val; true },
        Msg::Submit => { self.message = format!("Hello, {}!", self.name); true },
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <div>
        <input value={self.name.clone()} oninput={ctx.link().callback(|e: InputEvent| Msg::Update(e.data().unwrap_or_default()))} />
        <button onclick={ctx.link().callback(|_| Msg::Submit)}>{"Submit"}</button>
        <p>{ &self.message }</p>
        </div>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

Simple form input handling in Yew.

Let’s Try →
9

Yew Component with Conditional and Loop Combined

# yew/demo/conditional_loop.rs
use yew::prelude::*;

struct Model {
    show_first: bool,
}

enum Msg { Toggle, }

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Model { show_first: true }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg { Msg::Toggle => { self.show_first = !self.show_first; true } }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
        <div>
        { if self.show_first {
        html!{ for vec!["A", "B", "C"].iter().map(|i| html!{<p>{ i }</p>}) }
        } else {
        html!{ for vec!["X", "Y", "Z"].iter().map(|i| html!{<p>{ i }</p>}) }
        } }
        <button onclick={ctx.link().callback(|_| Msg::Toggle)}>{"Toggle"}</button>
        </div>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

Displays different lists based on a toggle.

Let’s Try →

Frequently Asked Questions about Yew

What is Yew?

Yew is a modern Rust framework for building client-side web applications using WebAssembly (Wasm), providing a reactive component-based architecture similar to React.

What are the primary use cases for Yew?

Single-page applications (SPA) in Rust. Interactive dashboards and data visualization. WebAssembly-based web games. Frontend for Rust backend services. High-performance, low-latency web UIs

What are the strengths of Yew?

Memory safety guaranteed by Rust compiler. High-performance UI rendering via WebAssembly. Strong type checking and compile-time guarantees. Reactive programming model similar to React. Can interoperate with existing JS libraries via wasm-bindgen

What are the limitations of Yew?

Compile times can be long for large projects. WebAssembly startup overhead may impact first-load time. Smaller ecosystem compared to JavaScript frameworks. Browser debugging is more complex than JS frameworks. Limited third-party component libraries compared to JS

How can I practice Yew typing speed?

CodeSpeedTest offers 9+ real Yew code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.