Skip to main content

Adding State

In this section 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'.

info

Here, rendering refers to building the layout of the component on which the 'render' was invoked. To 'render' is to build the layout. It does not render anything on the display of the device (no Views are created).

What you've built so far​

The following code shows your first Litho component from the previous section of the tutorial (see the Introducing Layout 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)))
}
}
}

Using useState to 'Like' the post​

The next step is to enhance the code by giving the user the ability to 'like' the post.

For this, you need to declare a component State using the useState hook (you need to declare an initial value):

val isLiked = useState { false }
note

useState can be only used in the render() function

Managing useState​

You can use the val isLiked for the following:

  • To access the state, use isLiked.value.

  • To update the state, use a lambda variant: isLiked.update { isLiked -> !isLiked }. See the following code for an example of how to update the state.

    • To learn more about the update options, see the useState page in the 'Main Concepts' section.

The following code uses a click (.onClick) on the Image component to update the state:

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 on each click, which matches the state as it switches between false and true.

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.

What next?​

You now have a component that is formatted with a Flexbox style and gives the user the ability to express a 'like'.

In the next section of the tutorial, Building Lists, you'll learn how to build lists in Litho with the Sections API.