Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More ergonomic use_state hook #1757

Closed
1 of 3 tasks
lukechu10 opened this issue Feb 23, 2021 · 2 comments · Fixed by #1780
Closed
1 of 3 tasks

More ergonomic use_state hook #1757

lukechu10 opened this issue Feb 23, 2021 · 2 comments · Fixed by #1780

Comments

@lukechu10
Copy link
Contributor

Problem
This is a continuation of #1026 (comment)

For the use_state hook, it would be more ergonomic if it only returned a struct rather than a tuple. It could be something like this:

#[derive(Clone)]
pub struct StateHandle<T> {
    value: Rc<T>,
}

impl<T> StateHandle<T> {
    /// Update the state and trigger a rerender.
    pub fn set(value: T) { }
}

impl<T> Deref for StateHandle<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target { }
}

It would be used like this:

let counter = use_state(|| 0);

html! {
    <button onclick=Callback::from(|_| counter.set(**counter + 1)) >{ "+1" }</button>
    <p>{ *counter }</p>
}

This way, when cloning the state into a closure (for callbacks), we only need to clone one Rc instead of two which should improve performance and ergonomics.

Even though this is a major change, it would be better to change it now rather then when Hooks are officially released.

Questionnaire

  • I'm interested in fixing this myself but don't know where to start
  • I would like to fix and I have a solution
  • I don't have time to fix this right now, but maybe later
@pickfire
Copy link

    <button onclick=Callback::from(|_| counter.set(*counter + 1)) >{ "+1" }</button>
    <p>{ *counter }</p>

I believe this could be more ergonomic.

@ranile ranile mentioned this issue Apr 21, 2021
3 tasks
@ranile
Copy link
Member

ranile commented Apr 22, 2021

I implemented it in #1780. I think we should make use_reducer work in a similar way. Thoughts? I'll be trying to implement that soon in that PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants