DEV Community

Cover image for Handling state dependent content in Jetpack Compose
Joseph Jazdzewski
Joseph Jazdzewski

Posted on

Handling state dependent content in Jetpack Compose

For almost all projects there will be state dependent content, this could be anything from error messages to whole pages. Different component based frameworks handle this issue differently. We will look at React and Angular's approaches and then look at the way Jetpack Compose handles it.

Angular

For example Angular's most common example is *ngIf

<element *ngIf="someState"></element>

The display logic is handled in the template file rather than the typescript file, this approach separates template logic and state logic. The template logic is very straight forward and readable for any new developer to understand.

React

React handles state dependent content in a not as straight forward way.

<>
    {
        this.state.someState && <p>some text</p>
    }
</>
Enter fullscreen mode Exit fullscreen mode

If you are not familiar with this syntax, it functions the same as an "if statement". In the code above, if "this.state.someState" is defined and is not false, [], {}, "", or 0 then <p>some text</p> will appear. This syntax is not completely straight forward to all developers.

JetPack Compose

Jetpack Compose combines these two approaches to produce a very straight forward and readable way to have state dependent content. If we are creating a carousel for our app, that changes the view when the next button is clicked.

In the code above, you can see that the render part of the code has a few "if statements" in it, which combines the previous two approaches when rendering state dependent content. Where there is no distinction between template and state logic and keeps the "if statement" more readable

Top comments (0)