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 ] | -------------------
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
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 } });
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.
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
useState hook do in a React Native component?useState hook is designed to let components keep track of values that can change, like user input or toggles.count with initial value 0 using useState?const [state, setState] = useState(initialValue);import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
export default function Counter() {
const [count, setCount] = useState(0);
return (
{count}
setCount(count + 1)} />
);
}setCount(count + 1), increasing count by 1.useState:import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
export default function Example() {
const [value, setValue] = useState;
return (
{value}
setValue('Hello')} />
);
}useState without parentheses, so it does not call the function to get state and setter.useState(), value and setValue are undefined, causing errors when used.isVisible between true and false each time a button is pressed. Which is the best way to update the state using useState to ensure the toggle works correctly even if updates happen quickly?const [isVisible, setIsVisible] = useState(false);
Pass the test and this pattern moves unknown