Hooks for Yew, inspired by streamich/react-use and alibaba/hooks.

Overview

Yew Hooks

Hooks for Yew, inspired by streamich/react-use and alibaba/hooks.

Hooks

State

  • use_toggle - tracks state of counterparts.
  • use_bool_toggle - tracks state of a boolean.
  • use_counter - tracks state of a number.

Lifecycles

  • use_effect_once - a modified use_effect hook that only runs once.
  • use_mount - calls mount callbacks.
  • use_unmount - calls unmount callbacks.
  • use_is_first_mount - checks if current render is first.
  • use_is_mounted - tracks if component is mounted.

Animations

  • use_timeout - schedules a timeout to invoke callback.
  • use_interval - schedules an interval to invoke callback.
  • use_update - returns a callback, which re-renders component when called.

Examples

use yew::prelude::*;

use yew_hooks::use_counter;

#[function_component(Counter)]
fn counter() -> Html {
    let counter = use_counter(0);

    let onincrease = {
        let counter = counter.clone();
        Callback::from(move |_| counter.increase())
    };
    let ondecrease = {
        let counter = counter.clone();
        Callback::from(move |_| counter.decrease())
    };
    let onincreaseby = {
        let counter = counter.clone();
        Callback::from(move |_| counter.increase_by(10))
    };
    let ondecreaseby = {
        let counter = counter.clone();
        Callback::from(move |_| counter.decrease_by(10))
    };
    let onset = {
        let counter = counter.clone();
        Callback::from(move |_| counter.set(100))
    };
    let onreset = {
        let counter = counter.clone();
        Callback::from(move |_| counter.reset())
    };
    
    html! {
        <div>
            <button onclick={onincrease}>{ "Increase" }</button>
            <button onclick={ondecrease}>{ "Decrease" }</button>
            <button onclick={onincreaseby}>{ "Increase by 10" }</button>
            <button onclick={ondecreaseby}>{ "Decrease by 10" }</button>
            <button onclick={onset}>{ "Set to 100" }</button>
            <button onclick={onreset}>{ "Reset" }</button>
            <p>
                <b>{ "Current value: " }</b>
                { *counter }
            </p>
        </div>
    }
}

Demo

Check out a live demo

You might also like...
egui: an easy-to-use immediate mode GUI in pure Rust
egui: an easy-to-use immediate mode GUI in pure Rust

🖌 egui: an easy-to-use GUI in pure Rust egui is a simple, fast, and highly portable immediate mode GUI library for Rust. egui runs on the web, native

Use C++ libraries from Rust

ritual ritual allows to use C++ libraries from Rust. It analyzes the C++ API of a library and generates a fully-featured crate that provides convenien

An easy to use command line project manager for projects using the ReCT programming language
An easy to use command line project manager for projects using the ReCT programming language

☢️ A powerful project manager for the ReCT programming language! ☢️ ReCTx makes your projects easier to manage by allowing you to configure everything

Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust.

Deno Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust. Features Secure by default. No file,

Rust bindings to Core Foundation and other low level libraries on Mac OS X and iOS

core-foundation-rs Compatibility Targets macOS 10.7 by default. To enable features added in macOS 10.8, set Cargo feature mac_os_10_8_features. To hav

Rust bindings and wrappers for GLib, GDK 3, GTK+ 3 and Cairo.

THIS REPOSITORY IS DEPRECATED SEE: https://github.com/rust-gnome rgtk Rust bindings and wrappers for GLib, GDK 3, GTK+ 3 and Cairo. Building rgtk expe

A simple, clean, and beautiful WYSIWYG Markdown editor and content-management system
A simple, clean, and beautiful WYSIWYG Markdown editor and content-management system

ScribeDown Current version: v0.0.1 Feature level: See the roadmap Beautiful, Clean, Writer-Oriented The goal of ScribeDown is to make Markdown the bes

A collection of components and widgets that are built for bevy_ui and the ECS pattern

Widgets for Bevy UI A collection of components and widgets that are built for bevy_ui and the ECS pattern. Current State This was started recently and

Unofficial Linux QQ client, based on GTK4 and libadwaita, developed with Rust and Relm4.
Unofficial Linux QQ client, based on GTK4 and libadwaita, developed with Rust and Relm4.

GTK QQ (WIP) Unofficial Linux QQ client, based on GTK4 and libadwaita, developed with Rust and Relm4. Screenshots Light Dark Note The two screenshots

Comments
  • How to store state from use_async via use_local_storage?

    How to store state from use_async via use_local_storage?

    this is more of a request for clarification/help rather than a bug

    i am trying to fetch data from a REST api once, and store it in local storage

    at the moment, i have successfully fetched the data, and render it in html, but am unable to store it in local storage

    relevant part of the code

    #[function_component(Guest)]
    pub fn guest() -> Html {
        let storage = use_local_storage::<String>("user".to_string());
        let state = use_async(async move { get_guest("https://matrix.org".to_owned()).await }); // get_guest returns Result<String, String>
        let get_guest_callback = {
            let state = state.clone();
            Callback::from(move |_| {
                state.run();
                let storage = storage.clone();
                if let Some(value) = &state.data {
                    storage.set(value.to_string())
                }
            })
        };
        if let Some(value) = &*storage {
            //
        } else {
            get_guest_callback.emit("");
        }
        html! {}
    }
    

    compiler diagnostic

    error[E0382]: borrow of moved value: `storage`
      --> src/components/atoms/guest.rs:40:27
       |
    28 |     let storage = use_local_storage::<String>("user".to_string());
       |         ------- move occurs because `storage` has type `UseLocalStorageHandle<String>`, which does not implement the `Copy` trait
    ...
    32 |         Callback::from(move |_| {
       |                        -------- value moved into closure here
    33 |             state.run();
    34 |             let storage = storage.clone();
       |                           ------- variable moved due to use in closure
    ...
    40 |     if let Some(value) = &*storage {
       |                           ^^^^^^^^ value borrowed here after move
       |
       = note: borrow occurs due to deref coercion to `Option<String>`
    note: deref defined here
      --> /home/isaac/.cargo/registry/src/github.com-1ecc6299db9ec823/yew-hooks-0.1.56/src/hooks/use_local_storage.rs:36:5
       |
    36 |     type Target = Option<T>;
       |     ^^^^^^^^^^^
    

    i am somewhat new to Rust, so there might be a feature that i've missed that could help solve this

    opened by imbev 2
  • Clippy fixes

    Clippy fixes

    This is mostly consideration but this passes following clippy checks

    -W clippy::all -W clippy::pedantic -W clippy::nursery -W clippy::cargo -A clippy::cargo-common-metadata -A clippy::module-name-repetitions -A clippy::must-use-candidate -A clippy::let-underscore-drop -A clippy::needless-pass-by-value -A clippy::cast-sign-loss -A clippy::cast-possible-wrap -A clippy::use-self -A clippy::implicit-hasher
    

    Notable allows:

    • cast-sign-loss/cast-possible-wrap - disabled because we are getting values from JS, and this is for sizes, I do not think that window size will overflow i32 anytime soon
    • implicit-hasher - while it would be nice to allow other hashers this overcomplicates the fixes
    • use-self - happens in web binds mostly and there is no way to fix this

    This probably needs to run tests and make sure it does not break anything, i.e. feel free to reject this(plus it is big)

    opened by aknarts 1
  • Rename web_socket to websocket

    Rename web_socket to websocket

    opened by allan2 0
Releases(v0.2.0)
  • v0.2.0(Nov 25, 2022)

    Upgrade Yew 0.20

    What's Changed

    • Upgrade to yew master branch by @jetli in https://github.com/jetli/yew-hooks/pull/14
    • improve use_infinite_scroll by @jetli in https://github.com/jetli/yew-hooks/pull/15
    • Rename web_socket to websocket by @allan2 in https://github.com/jetli/yew-hooks/pull/17
    • Rename the file to match mod.rs, fixes #18 by @aknarts in https://github.com/jetli/yew-hooks/pull/19
    • Rename fix by @aknarts in https://github.com/jetli/yew-hooks/pull/20
    • Clippy fixes by @aknarts in https://github.com/jetli/yew-hooks/pull/21
    • Update gloo to the latest version by @aknarts in https://github.com/jetli/yew-hooks/pull/22
    • improve use_infinite_scroll (#16) by @jetli in https://github.com/jetli/yew-hooks/pull/24

    Breaking Changes

    • use_web_socket renamed to use_websocket

    New Contributors

    • @allan2 made their first contribution in https://github.com/jetli/yew-hooks/pull/17
    • @aknarts made their first contribution in https://github.com/jetli/yew-hooks/pull/19

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.55...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.56(May 10, 2022)

    What's Changed

    • add prelude mod by @jetli in https://github.com/jetli/yew-hooks/pull/13

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.55...v0.1.56

    Source code(tar.gz)
    Source code(zip)
  • v0.1.55(May 7, 2022)

    What's Changed

    • add storage event listener to use_local_storage by @jetli in https://github.com/jetli/yew-hooks/pull/11
    • add use_infinite_scroll by @jetli in https://github.com/jetli/yew-hooks/pull/12

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.54...v0.1.55

    Source code(tar.gz)
    Source code(zip)
  • v0.1.54(Apr 24, 2022)

    What's Changed

    • fix clippy by @jetli in https://github.com/jetli/yew-hooks/pull/9
    • add use_clipboard hook by @jetli in https://github.com/jetli/yew-hooks/pull/10

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.53...v0.1.54

    Source code(tar.gz)
    Source code(zip)
  • v0.1.53(Mar 30, 2022)

    What's Changed

    • Add use_favicon by @jetli in https://github.com/jetli/yew-hooks/pull/8

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.52...v0.1.53

    Source code(tar.gz)
    Source code(zip)
  • v0.1.52(Mar 29, 2022)

    What's Changed

    • Add use_throttle_effect by @jetli in https://github.com/jetli/yew-hooks/pull/7

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.51...v0.1.52

    Source code(tar.gz)
    Source code(zip)
  • v0.1.51(Mar 29, 2022)

    What's Changed

    • Add use_debounce_effect by @jetli in https://github.com/jetli/yew-hooks/pull/6

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.50...v0.1.51

    Source code(tar.gz)
    Source code(zip)
  • v0.1.50(Mar 28, 2022)

    What's Changed

    • Add use_throttle_state by @jetli in https://github.com/jetli/yew-hooks/pull/5

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.49...v0.1.50

    Source code(tar.gz)
    Source code(zip)
  • v0.1.49(Mar 28, 2022)

    What's Changed

    • Add use_throttle by @jetli in https://github.com/jetli/yew-hooks/pull/4

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.48...v0.1.49

    Source code(tar.gz)
    Source code(zip)
  • v0.1.48(Mar 28, 2022)

    What's Changed

    • Refactor use_debounce by @jetli in https://github.com/jetli/yew-hooks/pull/2
    • Add use_debounce_state by @jetli in https://github.com/jetli/yew-hooks/pull/3

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.47...v0.1.48

    Source code(tar.gz)
    Source code(zip)
  • v0.1.47(Mar 27, 2022)

    What's Changed

    • Add use_debounce by @jetli in https://github.com/jetli/yew-hooks/pull/1

    New Contributors

    • @jetli made their first contribution in https://github.com/jetli/yew-hooks/pull/1

    Full Changelog: https://github.com/jetli/yew-hooks/compare/v0.1.46...v0.1.47

    Source code(tar.gz)
    Source code(zip)
  • v0.1.46(Mar 17, 2022)

A react-inspired UI library for building multimedia desktop apps with rust and vulkan.

narui A react-inspired UI library for building multimedia desktop apps with rust and vulkan. declarative UI with Ergonomics similar to React with hook

apertus° - open source cinema 42 Jan 1, 2023
An idiomatic GUI library inspired by Elm and based on gtk4-rs

An idiomatic GUI library inspired by Elm and based on gtk4-rs. Relm4 is a new version of relm that's built from scratch and is compatible with GTK4 an

Aaron Erhardt 722 Dec 31, 2022
Idiomatic, GTK+-based, GUI library, inspired by Elm, written in Rust

Relm Asynchronous, GTK+-based, GUI library, inspired by Elm, written in Rust. This library is in beta stage: it has not been thoroughly tested and its

null 2.2k Dec 31, 2022
A cross-platform GUI library for Rust, inspired by Elm

Iced A cross-platform GUI library for Rust focused on simplicity and type-safety. Inspired by Elm. Features Simple, easy-to-use, batteries-included AP

Héctor Ramón 17.5k Jan 2, 2023
SwiftUI Inspired UI Library written in rust

Mule (Definitely a Work in Progress) The night I started this project I was on the couch drinking a Moscow Mule.

null 40 Jun 22, 2022
A cross-platform GUI library for Rust, inspired by Elm

Iced A cross-platform GUI library for Rust focused on simplicity and type-safety. Inspired by Elm. Features Simple, easy-to-use, batteries-included AP

null 17.5k Dec 28, 2022
A UI-framework, built for speed and ease-of-use

A UI-framework, built for speed and ease-of-use. Focused on one thing, the best user-experience for the client and developer.

Vacaro 46 Dec 6, 2022
Example showing how to use tokio and egui together.

Example using tokio with egui This example uses reqwest to send an HTTP request to httpbin. The parsed response contains an increment value (as provid

Jay Oster 10 Dec 25, 2022
An easy-to-use, 2D GUI library written entirely in Rust.

Conrod An easy-to-use, 2D GUI library written entirely in Rust. Guide What is Conrod? A Brief Summary Screenshots and Videos Feature Overview Availabl

PistonDevelopers 3.3k Jan 1, 2023
A small tool to use along with i3/Sway to add CSS-powered decorations to your focused windows, for better usability.

glimmer What A tool for decorating i3 windows when they get focused, written in Rust. classic.mp4 Why When using i3-gaps I ran into the following prob

Daniel Acuña 26 Dec 17, 2022