import React, { useState, useReducer } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
export default function StateManagementDemo() {
const [countUseState, setCountUseState] = useState(0);
const [stateUseReducer, dispatch] = useReducer(reducer, { count: 0 });
return (
<View style={styles.container}>
<View style={styles.counterContainer} accessible accessibilityLabel="useState counter section">
<Text style={styles.counterText}>useState Counter: {countUseState}</Text>
<Button
title="Increment"
onPress={() => setCountUseState(countUseState + 1)}
accessibilityLabel="Increment useState counter"
/>
</View>
<View style={styles.counterContainer} accessible accessibilityLabel="useReducer counter section">
<Text style={styles.counterText}>useReducer Counter: {stateUseReducer.count}</Text>
<Button
title="Increment"
onPress={() => dispatch({ type: 'increment' })}
accessibilityLabel="Increment useReducer counter"
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
counterContainer: {
marginVertical: 20,
width: '80%',
alignItems: 'center',
},
counterText: {
fontSize: 24,
marginBottom: 10,
},
});We use useState to manage the first counter because it is simple and straightforward for a single value. The countUseState variable holds the current count, and setCountUseState updates it.
For the second counter, we use useReducer which is useful when state logic is more complex or involves multiple actions. Here, the reducer function handles an 'increment' action to increase the count. The dispatch function sends actions to the reducer.
Both counters have their own increment buttons that update their respective states independently. The layout uses View containers with styles for spacing and alignment. Accessibility labels are added for screen readers.