import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { createSlice } from '@reduxjs/toolkit';
// Redux slice
export const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1; },
decrement: state => { state.value -= 1; }
}
});
export const { increment, decrement } = counterSlice.actions;
export const counterReducer = counterSlice.reducer;
// React component
export default function CounterScreen() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<View style={styles.container}>
<Text style={styles.title}>Count</Text>
<Text style={styles.count}>{count}</Text>
<View style={styles.buttons}>
<Button title="-" onPress={() => dispatch(decrement())} />
<Button title="+" onPress={() => dispatch(increment())} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
title: { fontSize: 24, marginBottom: 10 },
count: { fontSize: 48, marginBottom: 20 },
buttons: { flexDirection: 'row', width: 150, justifyContent: 'space-between' }
});This example uses @reduxjs/toolkit to create a counter slice. The slice defines the initial state with value: 0 and two reducers: increment and decrement. These reducers update the state by increasing or decreasing the count.
In the React Native component, we use useSelector to read the current count from the Redux store. We use useDispatch to get the dispatch function.
When the user taps the '+' button, the increment action is dispatched, increasing the count. When the '-' button is tapped, the decrement action is dispatched, decreasing the count.
This setup keeps the UI and state logic clean and separated, making it easy to manage and scale.