Why I love Jetpack Compose and what makes it different from other declarative frameworks.
Hey android and web devs, in this article I am going to tell you some observations I made in jetpack compose.
Note: This is not the debate Compose vs React vs other frameworks.
Part 2: How Jetpack Compose optimizes its Recomposition?
For those who are new to Compose: Jetpack Compose | Android Developers
Jetpack Compose is Android’s modern toolkit for building native UI.
Let's begin.
In React.js, we write UI in a declarative manner and change the content using states. Whenever the state changes the whole UI gets rebuild and compared with Virtual DOM, and only makes changes that are changed.
Note: In React.js, all changes are being created, but it will only update the changed parts in DOM. But still, it was creating that whole tree for every change.
I thought Jetpack compose works in the same way until I discovered this.
UI is rendered only where it is needed.
React
Let me show an example.
React functional component
This is the simple counter code in React.
It’s working perfectly.
Adding log statement
The main thing is here.
I have added a console.log in that function, such that it will log whenever the UI renders.
Now if you increment that count, the console.log will be called every time.
As the console.log is called every time the state changes as expected.
Conclusion: In React.js, whenever the state changes the whole UI is being created in the place where the state is declared.
Jetpack Compose
Let’s see the same example in Compose
Here the state variable is count.
Whenever the button is clicked it increments the count.
As expected it renders the UI.
So what happens if we put a log inside that function
Here I added a log statement after the declaration of state variable count.
We should see the log printed in the terminal if Compose works similar to React.
Uh no!! It was printed only once. What is happening here?
We can see that the count is used only inside the Column context. So re-rendering all the components is unnecessary.
To prove this theory, we can add that count state to the log function.
As I said I have added the count variable in that log function.
Tada :), Now it's printed every time the state changes.
Conclusion: UI is re-rendered wherever the state needs to be changed.
Actually, I don’t know the reason, if I am able to find it I will definitely write an article. But for now, it gives me hope that it does not make any performance problems.
Key: I assume it happens, in react we return the UI, so it needs to be called every time. But in Compose the UI is emitted by calling functions.
Thank you for reading my articles. If you wish to support me, you can leave a clap and it will motivate me to publish more articles. Thanks again, I hope you learned something new.
Follow me on Twitter
Happy coding : )