import React, { useReducer } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const initialState = 0;
function reducer(state, action) {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
case 'reset':
return 0;
default:
return state;
}
}
export default function Counter() {
const [count, dispatch] = useReducer(reducer, initialState);
return (
<View style={styles.container}>
<Text style={styles.title}>Counter App</Text>
<Text style={styles.count}>{count}</Text>
<View style={styles.buttons}>
<Button title="+" onPress={() => dispatch({ type: 'increment' })} />
<Button title="-" onPress={() => dispatch({ type: 'decrement' })} />
<Button title="Reset" onPress={() => dispatch({ type: 'reset' })} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
title: { fontSize: 24, marginBottom: 20 },
count: { fontSize: 48, marginBottom: 20 },
buttons: { flexDirection: 'row', justifyContent: 'space-between', width: 200 }
});We use the useReducer hook to manage the counter state instead of useState. The reducer function takes the current state and an action, then returns the new state based on the action type.
We handle three actions: increment adds 1, decrement subtracts 1, and reset sets the count back to 0.
The buttons dispatch these actions when pressed, updating the count displayed on the screen.