import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { View, Text, Button, StyleSheet } from 'react-native';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1; },
decrement: state => { state.value -= 1; }
}
});
const store = configureStore({
reducer: { counter: counterSlice.reducer }
});
function CounterScreen() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<View style={styles.container}>
<Text style={styles.title}>Counter App</Text>
<Text style={styles.count}>Count: {count}</Text>
<View style={styles.buttons}>
<Button title="-" onPress={() => dispatch(counterSlice.actions.decrement())} />
<Button title="+" onPress={() => dispatch(counterSlice.actions.increment())} />
</View>
</View>
);
}
export default function App() {
return (
<Provider store={store}>
<CounterScreen />
</Provider>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
title: { fontSize: 24, marginBottom: 20 },
count: { fontSize: 32, marginBottom: 20 },
buttons: { flexDirection: 'row', width: 120, justifyContent: 'space-between' }
});We created a counterSlice using Redux Toolkit's createSlice function. It holds the counter state and two reducers: increment and decrement. The store is configured with this slice's reducer.
In the CounterScreen component, we use useSelector to read the current count from the Redux store. We use useDispatch to get the dispatch function and call the increment or decrement actions when the buttons are pressed.
The whole app is wrapped in Provider to give access to the Redux store.
This setup keeps state management clean and easy to maintain.