0
0
React Nativemobile~15 mins

useState hook in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Counter Screen
A simple screen that shows a number and lets the user increase it by pressing a button.
Target UI
-------------------
|   Counter: 0    |
|                 |
|  [ Increase ]   |
-------------------
Display a number starting at 0
Add a button labeled 'Increase'
When the button is pressed, the number increases by 1
Use the useState hook to manage the number state
Starter Code
React Native
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function CounterScreen() {
  // TODO: Add state for counter here

  return (
    <View style={styles.container}>
      <Text style={styles.counterText}>Counter: 0</Text>
      <Button title="Increase" onPress={() => { /* TODO: Increase counter */ }} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  counterText: {
    fontSize: 32,
    marginBottom: 20
  }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function CounterScreen() {
  const [counter, setCounter] = useState(0);

  return (
    <View style={styles.container}>
      <Text style={styles.counterText}>Counter: {counter}</Text>
      <Button title="Increase" onPress={() => setCounter(counter + 1)} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  counterText: {
    fontSize: 32,
    marginBottom: 20
  }
});

We import useState from React to create a state variable called counter starting at 0. The setCounter function updates this state. The Text component shows the current value of counter. When the user presses the button, the onPress handler calls setCounter(counter + 1) to increase the number by one. This updates the UI automatically because React re-renders the component when state changes.

Final Result
Completed Screen
-------------------
|   Counter: 0    |
|                 |
|  [ Increase ]   |
-------------------
When the user taps the 'Increase' button, the number shown after 'Counter:' increases by 1 each time.
Stretch Goal
Add a 'Decrease' button that lowers the counter by 1 but never below 0.
💡 Hint
Create another Button with title 'Decrease' and in onPress, use setCounter(Math.max(counter - 1, 0)) to prevent negative numbers.