machfour
machfour

Reputation: 2709

When to prefer passing State<T> vs T itself

Are there any circumstances in which one should prefer one of these alternatives over the other?

@Composable
fun <T> Foo(data: State<T>) { ... }

compared to

@Composable
fun <T> Foo(data: T) { ... }

Or with mutable states,

@Composable
fun <T> Foo(data: MutableState<T>) { ... }

compared to

@Composable
fun <T> Foo(data: T, setData: (T) -> Unit) { ... }

Clearly one advantage of having a setData lambda is you can intercept the set operation, but I'm more interested from a Compose perspective. Are there any implications for the compose compiler or how recomposition will work?

Upvotes: 5

Views: 586

Answers (1)

S Haque
S Haque

Reputation: 7281

I would prefer

@Composable
fun <T> Foo(data: T) { ... }

and

@Composable
fun <T> Foo(data: T, setData: (T) -> Unit) { ... }

over their respective counter parts. Reasons are:

  • For the first one, In case you have to change State data structure in future, you have to refactor all the Composable for actually no reason, as State<T> does not bring any extra accessibility to your Composable. Besides, in the sample projects and live demo from Google, I have always seen them to use T
  • For the second one, suppose you are using the MutableState two or more composable, for example ComposableA and ComposableB, both composable can change each others state if they make any update to MutableState which might create issues in some situation. If ComposableP is their least common parent, I would prefer declaring MutableState in the parent and pass T and callbacks to the ComposableA and ComposableB. You can compare it State Hoisting

Upvotes: 0

Related Questions