ReduxToolkit in ReactNative
What is Redux Toolkit?
Redux Toolkit is the official recommended way to write Redux logic. It is a set of tools and best practices designed to simplify the process of using Redux and manage the code.
How Redux Toolkit Improves Redux
Let’s revisit the example code with explanations of how Redux Toolkit simplifies and improves the Redux workflow.
Project Structure
MyNewProject/
├── App.tsx
├── Counter.tsx
├── redux/
│ ├── store.ts
│ └── counterSlice.ts
├── node_modules/
├── package.json
├── tsconfig.json
└── ...
Install Required Packages
npm install @reduxjs/toolkit react-redux
redux/store.ts
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
- configureStore: Simplifies store setup with built-in best practices and integrates Redux DevTools by default.
Benefit : Single Object Configuration: Combines multiple reducers in a single configuration object.
What is a Reducer?
In Redux, a reducer is a function that determines changes to an application’s state. It uses the action it receives to decide this change. A reducer takes two arguments: the current state and an action. Based on the action type, it returns a new state.
Why We Need Reducers
- State Management: Reducers are essential for managing the state of your application. They specify how the application’s state changes in response to actions.
- Pure Functions: Reducers are pure functions, meaning they do not produce side effects. This makes the state changes predictable and easier to debug.
- Centralized Logic: By having all the state transitions in one place, the logic of how your state evolves is centralized, making the application easier to maintain and reason about.
redux/counterSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface CounterState {
value: number;
}
const initialState: CounterState = {
value: 0,
};
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
- createSlice: Automatically generates action creators and action types based on the provided reducers, reducing boilerplate code.
Benefit: Immer Integration: Uses Immer to handle immutable state updates in a concise and readable way.
App.tsx
import React from 'react';
import { Provider } from 'react-redux';
import { store } from './redux/store';
import Counter from './Counter';
const App = () => {
return (
<Provider store={store}>
<Counter />
</Provider>
);
};
export default App;
Provider Integration: Standard React Redux provider setup, making the Redux store available to the entire app.
Counter.tsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { StyleSheet, View, Text, Button } from 'react-native';
import { RootState, AppDispatch } from './redux/store';
import { increment, decrement } from './redux/counterSlice';
const Counter = () => {
const count = useSelector((state: RootState) => state.counter.value);
const dispatch: AppDispatch = useDispatch();
return (
<View style={styles.container}>
<Text style={styles.text}>Count: {count}</Text>
<Button title="Increment" onPress={() => dispatch(increment())} />
<Button title="Decrement" onPress={() => dispatch(decrement())} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 24,
marginBottom: 10,
},
});
export default Counter;
- useSelector: Simplifies accessing the Redux store state.
- useDispatch: Simplifies dispatching actions.
Summary
Redux Toolkit significantly reduces the complexity and boilerplate associated with traditional Redux. It provides a set of tools and best practices that streamline the process of writing and maintaining Redux logic, making it more accessible and easier to manage.
This leads to more consistent, maintainable, and readable code, ultimately improving the developer experience.
Thank you for reading.