Skip to main content

Adding State

In this part of the tutorial, you'll learn about useState, one of Litho's Hooks.

useState enables a component to persist and update a single value across renders.

First, you start with the component built in previous part of the tutorial (see the Components and Props page):

class PostStyledKComponent(val post: Post) : KComponent() {
override fun ComponentScope.render(): Component {
return Column {
child(
Row(alignItems = YogaAlign.CENTER, style = Style.padding(all = 8.dp)) {
child(
Image(
drawable = drawableRes(post.user.avatarRes),
style = Style.width(36.dp).height(36.dp).margin(start = 4.dp, end = 8.dp)))
child(Text(text = post.user.username, textStyle = Typeface.BOLD))
})
child(
Image(
drawable = drawableRes(post.imageRes),
scaleType = ImageView.ScaleType.CENTER_CROP,
style = Style.aspectRatio(1f)))
}
}
}

The next step is adding the ability to 'like' a post.

For this, you need to declare a component State using the useState hook, in which you always need to declare an initial value (useState can be only used in the render() function):

val isLiked = useState { false }

To access a state, use isLiked.value. To update it, use a lambda variant isLiked.update { isLiked -> !isLiked }. To learn more about update options, see the useState page.

You'll update the state after clicking on the Image component:

Image(
drawable =
drawableRes(
if (isLiked.value) R.drawable.ic_baseline_favorite_24
else R.drawable.ic_baseline_favorite_border_24),
style =
Style.width(32.dp).height(32.dp).margin(all = 6.dp).onClick {
isLiked.update { isLiked -> !isLiked }
})

You can see the implemented behaviour in the video clip below (notice how the heart icon changes when clicked).

Key Points:

  • useState - a Hook that enables a component to persist and update a single value across renders.
  • render() - you can use useState Hook only in the render() function.