Do we have short syntx for remember in Compose? ``...
# compose
s
Do we have short syntx for remember in Compose?
Copy code
var imageBitmap by remember { mutableStateOf<ImageBitmap?>(null) }
SwiftUI syntx read so much better @State var someValue = ""
p
There used to be a
state
function/delegate. It's deprecated now
You can look into its source and Ctrl+c Ctrl+v into your project
a
we found that
Copy code
var someValue by state { "" }
led to a lot of confusion for developers in terms of how and where observable state holders and property delegates can be created, so we encourage the longer version as the preferred approach. Decomposing it into the distinct mechanisms of
remember
to create persistence in composition and
mutableStateOf
to create an observable state holder led to better understanding of how things work and what's possible.
If you find yourself doing
Copy code
var someValue by remember { mutableStateOf("") }
often and repeated enough to where it gets onerous or noisy to read, it's often a sign that you want to create a class to hold several observable properties as part of one concept, e.g.
Copy code
class MyState(
  foo: Foo,
  bar: Bar
) {
  var foo by mutableStateOf(foo)
  var bar by mutableStateOf(bar)
    private set
}
and use it with a single
remember
, potentially as part of a default argument expression to allow the state to be hoisted to the caller:
Copy code
@Composable fun MyComposable(
  state: MyState = remember { MyState(defaultFoo, defaultBar) }
) {
👍 1
this all feeds into intended design patterns for compose code:
@Composable
functions emit UI based on state provided to them via parameters; the more private state you can hoist to be controllable by the caller/testable in isolation, outside of composition, the nicer your API becomes to work with. The pattern of
remember
expressions as default arguments above help balance caller convenience with flexibility when they want/need it, as opposed to creating a lot of private state.
👍 2
t
You could also just define your own shortcut:
Copy code
@Composable
fun <T>rememberState(block: () -> T) = remember { mutableStateOf(block()) }
☝️ 3
a
Yep, though if you do I'd recommend marking it
inline
4