pavi2410 / useCompose

Headless @Composable hooks that drive UI logic. Inspired by TanStack & React.
MIT License
28 stars 5 forks source link

Should useState be updated to *not* use the setter from MutableState? #6

Closed thevoiceless closed 2 years ago

thevoiceless commented 2 years ago

Context: https://www.reddit.com/r/androiddev/comments/rqdv5g/there_are_three_ways_to_declare_a_mutablestate/

tl;dr:

@Composable
fun Test() {
    val (value, setValue) = remember { mutableStateOf(0) }
    println(value)
    setValue(value + 1)
    println(value)
}

will output

0
0

In light of that, perhaps useState should be updated? Something like:

@Composable
fun <T> useState(defaultValue: T): Pair<T, (T) -> Unit> {
    var state by remember { mutableStateOf(defaultValue) }
    return Pair(state, { state = it }) // or `return state to { state = it }`
}
pavi2410 commented 2 years ago

Thanks for reporting this issue. I'll try reproducing this on Compose (with and without useCompose) as well as React to test the appropriate behaviour.

pavi2410 commented 2 years ago

Tried the following cases

thevoiceless commented 2 years ago

Interesting! Thanks for looking into it :)