stringResource() causing recompose of composition

521 Views Asked by At

I am beginner at jetpack compose. I was debugging recomposition but suddenly I saw a unusual recomposition in Header compose function when app start. I find out the reason or culprit for the recomposition that I used in Header compose function to get string text by stringResource().. If I use context.getString() or hardcode string value instead of stringResource() then I got no recomposition.

This code when showing the recomposition

@Composable
fun MainScreen() {
    Header()
}

@Composable
fun Header() {
   Text(
    text = stringResource(id = R.string.app_name)
   )
}

But If I use these codes No more recomposition. But why?

@Composable
fun MainScreen() {
    Header()
}

@Composable
fun Header() {
   val context = LocalContext.current
   Text(
    text = context.getString(R.string.app_name)
   )
}

So what can I do for get rid of recomposition when using stringResource() into compose functions

2

There are 2 best solutions below

1
On

First of all, this behavior shouldn't be happening, I recommend creating a clean project and trying again.

But... to avoid recomposing inside Composable, the Effect API would be useful:

    val context = LocalContext.current
    var appName = ""
        
    LaunchedEffect(Unit) {
        appName = context.getString(R.string.app_name)
    }
    Text(
        text = appName
    )

The codes inside the LaunchedEffect block are only executed once, even if the recomposition happens. Documentaion of api Side Effects

1
On

if you have the value saved in the res/values/strings.xml file then using compose the only thing you will need to do is calling the stringResource(R.string.app_name). Jetpack Compose handles getting the resource on its own. you wont even need to get it from your Context. see here for docs on resource.

that should not cause recomposing every time but if it does it is always a good practice to save your values inside of a remember so that it knows not to recompose every time. the problem might be from a different part of your code.