Hey everyone, What is the correct way of dealing with state and ComposeNavigation? I’m facing an iss...
h
Hey everyone, What is the correct way of dealing with state and ComposeNavigation? I’m facing an issue where the same code works fine for simple composable but doesn’t work when wrapped inside of a NavHost. Code snippets and details in the thread…
Copy code
setContent {
    val (isLightTheme, setLightTheme) = savedInstanceState { true }
    McComposeTheme(lightTheme = isLightTheme) {
        HomeScreen(onClick = { setLightTheme(!isLightTheme) })
    }
}
This code works perfectly fine, just a composable with state.
Copy code
setContent {
    val (isLightTheme, setLightTheme) = savedInstanceState { true }
    McComposeTheme(lightTheme = isLightTheme) {
        val navController = rememberNavController()
        NavHost(navController, startDestination = "home") {
            composable("home") {
                HomeScreen(onClick = { setLightTheme(!isLightTheme) })
            }
        }
    }
}
The issue is in this code, where I’m using
NavHost
The state is not persisted and I’m unable to toggle the light and dark theme.
j
You can apply "state hoisting", which will make your composables more reusable and more testable and generally higher quality anyway. It will also have the side effect of ensuring you never loose any of your state when code paths change. I found this video to be a reasonable intro:

https://www.youtube.com/watch?v=GT1VJweyNr0

And here are the official docs: https://developer.android.com/jetpack/compose/state#stateless-composables
h
Hi @jim, the state I'm using is for dark/light theme and I'm passing it to my ComposeTheme. This code snippet is from my MainActivity so I'm wondering where should I hoist my state as this the top level for me. Please correct me if I'm wrong here.
j
There are many factors that would help you decide how high to hoist. A few example questions are: • Do I want the state to persist across app restarts? in which case I might store it to a local configuration database. • Do I want my state to synchronize across all my user's devices? In which case, I need to store the data on a server and associate it with the user so I can synchronize it when they log in from a different device. • Do I want the data to match only the activity lifecycle? In which case, I might hoist it up out of the root composable and into the activity. The point is, you have lots of choices, and the root composable is not necessarily the end of the road. It all depends on the intended lifecycle of that data.