Skip to content

Rule feature request: Using derivedStateOf without any State object in calculation #88

@svenjacobs

Description

@svenjacobs

Currently there is no (lint) warning when using derivedStateOf without accessing any State object in its calculation, which can lead to unexpected behaviour. Since no State object is read, the derived value will never update which however might not be obvious just by looking at the code.

Let's take the following Composable for example:

@Composable
fun Amount(
    amount: Int,
    modifier: Modifier = Modifier,
) {
    val isZeroAmount by remember { derivedStateOf { amount == 0 } }

    Box(modifier = modifier) {
        if (isZeroAmount) {
            Text("Amount: Is zero")
        } else {
            Text("Amount: $amount")
        }
    }
}

If amount is 1 initially and becomes 0 on the next recomposition, the Composable will incorrectly display Amount: 0 instead of Amount: Is zero.

This might for instance happen when a State variable with by delegation is changed to a plain type.
The correct code for this case would be:

@Composable
fun Amount(
    amount: State<Int>,
    modifier: Modifier = Modifier,
) {
    val isZeroAmount by remember { derivedStateOf { amount.value == 0 } }

    Box(modifier = modifier) {
        if (isZeroAmount) {
            Text("Amount: Is zero")
        } else {
            Text("Amount: ${amount.value}")
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions