Parent knows best: State Hoisting in Android

Introduction:
Imagine building a React or jetpack compose app where ever child component manages its own state. Chaos ,right? State hoisting is the design pattern that saves us from this mess. Let’s break this down.
Key points to cover:
1) What’s the problem?
-Apps become hard to debug when state is scattered. An example is when two composables need the same data such as dark mode toggle.
2) What is state hoisting?
State hoisting refers to moving state to a common parent i.e, a single source of truth.
A simple analogy of the above definition is like when a school principal (parent) announces rules for all classrooms(children).
Reasons as to why we shoud hoist state:
1) Reusability- Stateless composables work anywhere such as a button that accepts any onClick.
2) Predictability- Parent controls logic, children just display/notify.
3) Testability- Easier to mock state when it is centralized.
Rules of State Hoisting:
1) State goes up, events go down.
2) Use immutable values in children i.e, val not var.
3) Prefix event handlers with on (e.g onClick, onValueChange)
Conclusion:
State hoisting turns chaotic UIs into predictable, reusable systems. Start small (lift state to the nearest parent), and soon you will architect apps like a pro.
Reference:
Subscribe to my newsletter
Read articles from David Njoka directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

David Njoka
David Njoka
Passionate about Jetpack Compose, coroutines, and making tech fun.