Skip to content

Why does use_state not update its value in a simple interval counter? #3091

Answered by WorldSEnder
uvizhe asked this question in Q&A
Discussion options

You must be logged in to vote

The UseStateHandle you get during rendering captures and indefinitely reflects the value the state had at the time of rendering. This is so that using the state handle as a cache key works correctly, and compares the old vs the new value, when using the "same" handle from successive renders.

As such, *counter + 1 always computes the same value: 1 + the counter value at the time of rendering. What you want to use is Reducible. Reducible::reduce does get access to the current value, even when an action is dispatched later:

use std::rc::Rc;

#[derive(Clone)]
struct Counter { value: u32 }

impl Reducible for Counter {
    type Action = (); // Only one action. Could use an enum CounterAction {…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by uvizhe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants