Bird
Raised Fist0
Android Kotlinmobile~20 mins

Derived state in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Derived State Example
This screen shows how to use derived state in Jetpack Compose to update UI based on user input.
Target UI
-------------------------
| Enter your name:       |
| [______________]       |
|                         |
| Greeting:               |
| Hello, [Name]!          |
-------------------------
Add a TextField for user to enter their name.
Use derived state to create a greeting message that updates as the user types.
Display the greeting message below the TextField.
Greeting should say 'Hello, [Name]!' or 'Hello!' if no name is entered.
Starter Code
Android Kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun DerivedStateScreen() {
    val name = remember { mutableStateOf("") }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(text = "Enter your name:")
        TextField(
            value = name.value,
            onValueChange = { /* TODO: Update name state */ },
            modifier = Modifier.padding(vertical = 8.dp)
        )

        // TODO: Add derived state for greeting message

        // TODO: Display greeting message
    }
}
Task 1
Task 2
Task 3
Solution
Android Kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun DerivedStateScreen() {
    val name = remember { mutableStateOf("") }

    // Derived state for greeting message
    val greeting by remember {
        derivedStateOf {
            if (name.value.isNotBlank()) "Hello, ${name.value}!" else "Hello!"
        }
    }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(text = "Enter your name:")
        TextField(
            value = name.value,
            onValueChange = { name.value = it },
            modifier = Modifier.padding(vertical = 8.dp)
        )

        Text(text = "Greeting:")
        Text(text = greeting, style = MaterialTheme.typography.bodyLarge)
    }
}

We use mutableStateOf to hold the user's input name. The derivedStateOf creates a new state that depends on name.value. It updates automatically when the name changes, producing a greeting message. This way, the UI updates efficiently only when the derived greeting changes. The greeting is shown below the TextField, showing 'Hello, [Name]!' if the user typed a name, or just 'Hello!' if empty.

Final Result
Completed Screen
-------------------------
| Enter your name:       |
| [John]                 |
|                         |
| Greeting:               |
| Hello, John!            |
-------------------------
User types their name in the TextField.
Greeting text updates live to say 'Hello, [Name]!'.
If TextField is empty, greeting shows 'Hello!'.
Stretch Goal
Add a clear button inside the TextField to erase the name quickly.
💡 Hint
Use the trailingIcon parameter of TextField with an IconButton that sets name.value to empty string.

Practice

(1/5)
1. What is the main purpose of derivedStateOf in Android Kotlin Compose?
easy
A. To create a value that automatically updates when its dependencies change
B. To store data permanently on the device
C. To launch a new screen in the app
D. To handle user input events

Solution

  1. Step 1: Understand what derived state means

    Derived state is a value computed from other state values that updates automatically when those values change.
  2. Step 2: Identify the role of derivedStateOf

    derivedStateOf creates such a derived value in Compose, so the UI stays in sync without extra storage.
  3. Final Answer:

    To create a value that automatically updates when its dependencies change -> Option A
  4. Quick Check:

    Derived state = auto-updating computed value [OK]
Hint: Derived state updates automatically from other states [OK]
Common Mistakes:
  • Confusing derived state with permanent storage
  • Thinking it triggers navigation
  • Assuming it handles user input directly
2. Which of the following is the correct syntax to create a derived state in Jetpack Compose?
easy
A. val derivedValue = mutableStateOf { someState.value * 2 }
B. val derivedValue = remember { mutableStateOf(0) }
C. val derivedValue = state { someState.value * 2 }
D. val derivedValue = derivedStateOf { someState.value * 2 }

Solution

  1. Step 1: Recall the correct function for derived state

    The function derivedStateOf is used to create derived state in Compose.
  2. Step 2: Check the syntax correctness

    val derivedValue = derivedStateOf { someState.value * 2 } uses derivedStateOf with a lambda returning a computed value, which is correct syntax.
  3. Final Answer:

    val derivedValue = derivedStateOf { someState.value * 2 } -> Option D
  4. Quick Check:

    Use derivedStateOf with a lambda for derived state [OK]
Hint: Look for derivedStateOf with a lambda block [OK]
Common Mistakes:
  • Using mutableStateOf instead of derivedStateOf
  • Forgetting the lambda braces {}
  • Using state instead of derivedStateOf
3. Given the code below, what will be the output of derivedValue.value after count.value = 5?
val count = mutableStateOf(0)
val derivedValue = derivedStateOf { count.value * 3 }
count.value = 5
println(derivedValue.value)
medium
A. 15
B. 5
C. 0
D. Error at runtime

Solution

  1. Step 1: Understand the initial states

    Initially, count.value is 0, so derivedValue.value is 0 * 3 = 0.
  2. Step 2: Update count and check derived value

    After setting count.value = 5, derivedValue.value recalculates as 5 * 3 = 15 automatically.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    Derived state recalculates on dependency change [OK]
Hint: Derived state updates instantly when dependencies change [OK]
Common Mistakes:
  • Assuming derivedValue does not update after count changes
  • Confusing derivedValue with count.value
  • Expecting runtime error due to state change
4. Identify the error in the following code that tries to create a derived state:
val count = mutableStateOf(10)
val derivedValue = derivedStateOf(count.value * 2)
medium
A. mutableStateOf cannot be used with integers
B. derivedValue should be mutableStateOf, not derivedStateOf
C. derivedStateOf requires a lambda, not a direct value
D. No error, code is correct

Solution

  1. Step 1: Check the usage of derivedStateOf

    derivedStateOf expects a lambda expression to compute the value lazily and track dependencies.
  2. Step 2: Identify the mistake in the code

    The code passes count.value * 2 directly, which evaluates immediately, not inside a lambda.
  3. Final Answer:

    derivedStateOf requires a lambda, not a direct value -> Option C
  4. Quick Check:

    derivedStateOf needs a lambda block {} [OK]
Hint: Always use curly braces {} with derivedStateOf [OK]
Common Mistakes:
  • Passing direct value instead of lambda
  • Confusing mutableStateOf and derivedStateOf
  • Assuming no error in syntax
5. You want to display a message in your Compose UI that shows "Even" or "Odd" depending on a number state. Which is the best way to implement this using derived state?
val number = mutableStateOf(0)
// Your code here
Text(text = evenOdd.value)
hard
A. val evenOdd = derivedStateOf(number.value % 2)
B. val evenOdd = derivedStateOf { if (number.value % 2 == 0) "Even" else "Odd" }
C. val evenOdd = remember { mutableStateOf("Even") }
D. val evenOdd = mutableStateOf(if (number.value % 2 == 0) "Even" else "Odd")

Solution

  1. Step 1: Understand the requirement for dynamic text

    The text must update automatically when number.value changes, showing "Even" or "Odd".
  2. Step 2: Choose the correct derived state implementation

    val evenOdd = derivedStateOf { if (number.value % 2 == 0) "Even" else "Odd" } uses derivedStateOf with a lambda that returns "Even" or "Odd" based on number.value, which updates automatically.
  3. Final Answer:

    val evenOdd = derivedStateOf { if (number.value % 2 == 0) "Even" else "Odd" } -> Option B
  4. Quick Check:

    Use derivedStateOf with conditional logic for dynamic UI text [OK]
Hint: Use derivedStateOf with if-else for dynamic text [OK]
Common Mistakes:
  • Using mutableStateOf without updating on number change
  • Forgetting to use a lambda in derivedStateOf
  • Using derivedStateOf incorrectly without returning string
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard