Search⌘ K
AI Features

Taking Advantage of Redux Toolkit for Creating Actions

Explore how to leverage Redux Toolkit to simplify Redux implementation in React Native. Learn to convert reducers into slices, create asynchronous thunks for data fetching, and replace React context with Redux for global state management. This lesson guides you through creating actions, handling async logic, and integrating Redux hooks in functional components to improve your app's data flow.

Our reducer is very limited so far. We can’t use it directly to fetch data because, as the rules of reducers state, reducers cannot be used to do any asynchronous logic. If we were writing our app sometime around 2018 or 2019, we would probably create a separate actions file, manually configure Redux middleware functions to manage asynchronous API calls, and finally proceed to write the fetching actions. Luckily, we can now take advantage of Redux Toolkit, which comes bundled with all the necessary helper functions and a utility called createSliceIn Redux lingo, a slice is a collection of reducers and actions for a single feature in our app.

Converting reducers to slices

Let’s convert our likedImages reducer into a Redux Toolkit slice:

Javascript (babel-node)
//reducers/likedImages.js
import { createSlice } from "@reduxjs/toolkit";
// Create a Redux slice for likedImages
export const likedImagesSlice = createSlice({
name: "likedImages",
initialState: [], // Initial state is an empty array
reducers: {
likeImage: (state, action) => {
// Reducer function for liking an image
const newLikedImage = action.payload;
return [...state, newLikedImage];
},
unLikeImage: (state, action) => {
// Reducer function for unliking an image
const stateWithoutLikedImage = state.filter(
(item) => item !== action.payload
);
return stateWithoutLikedImage;
},
},
});
// Export action creators and reducer from the slice
export const { likeImage, unLikeImage } = likedImagesSlice.actions;
export default likedImagesSlice.reducer;

Here’s an explanation of the above code:

    ...