“Redux Toolkit: Creating and Using Multiple Slices in React”-(React No-29)

Gondi
3 min readOct 10, 2024

--

In Redux Toolkit, slices are used to manage pieces of the global state by combining actions and reducers in a single unit. Creating multiple slices helps you manage different parts of your application’s state more cleanly and modularly.

Here’s an example of how you can create multiple slices in Redux Toolkit in a React application:

1. Install Redux Toolkit and React-Redux

First, ensure you have Redux Toolkit and React-Redux installed:

npm install @reduxjs/toolkit react-redux

2. Create Multiple Slices

Let’s say we want to manage two features in our app: user and posts. We’ll create two slices—one for user state and one for posts state.

a) User Slice (userSlice.js)

import { createSlice } from '@reduxjs/toolkit';

const initialState = {
name: '',
email: '',
isLoggedIn: false,
};

const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
login: (state, action) => {
state.name = action.payload.name;
state.email = action.payload.email;
state.isLoggedIn = true;
},
logout: (state) => {
state.name = '';
state.email = '';
state.isLoggedIn = false;
},
},
});

export const { login, logout } = userSlice.actions;
export default userSlice.reducer;

b) Posts Slice (postsSlice.js)

import { createSlice } from '@reduxjs/toolkit';

const initialState = {
posts: [],
loading: false,
};

const postsSlice = createSlice({
name: 'posts',
initialState,
reducers: {
fetchPostsStart: (state) => {
state.loading = true;
},
fetchPostsSuccess: (state, action) => {
state.posts = action.payload;
state.loading = false;
},
fetchPostsFailure: (state) => {
state.loading = false;
},
},
});

export const { fetchPostsStart, fetchPostsSuccess, fetchPostsFailure } = postsSlice.actions;
export default postsSlice.reducer;

3. Configure the Store (store.js)

You need to combine these slices in your Redux store. Here’s how you can configure the store to include both the user and posts slices:

import { configureStore } from '@reduxjs/toolkit';
import userReducer from './userSlice';
import postsReducer from './postsSlice';

const store = configureStore({
reducer: {
user: userReducer,
posts: postsReducer,
},
});

export default store;

4. Provide the Store to Your React App (index.js)

To use Redux in your React app, wrap your application with the Provider component from react-redux and pass it the store:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

5. Use the Slices in a Component (App.js)

You can now use the Redux state and dispatch actions from your slices in a component. Here’s an example of how to use both the user and posts slices in a component:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { login, logout } from './userSlice';
import { fetchPostsStart, fetchPostsSuccess, fetchPostsFailure } from './postsSlice';

const App = () => {
const dispatch = useDispatch();
const user = useSelector((state) => state.user);
const posts = useSelector((state) => state.posts);

const handleLogin = () => {
dispatch(login({ name: 'John Doe', email: 'john@example.com' }));
};

const handleLogout = () => {
dispatch(logout());
};

const fetchPosts = async () => {
dispatch(fetchPostsStart());
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
dispatch(fetchPostsSuccess(data));
} catch (error) {
dispatch(fetchPostsFailure());
}
};

return (
<div>
<h1>User Info</h1>
{user.isLoggedIn ? (
<div>
<p>Name: {user.name}</p>
<p>Email: {user.email}</p>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<button onClick={handleLogin}>Login</button>
)}

<h1>Posts</h1>
{posts.loading ? (
<p>Loading...</p>
) : (
<div>
<button onClick={fetchPosts}>Fetch Posts</button>
<ul>
{posts.posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)}
</div>
);
};

export default App;

6. Run the Application

Now you can run the application, and you’ll have multiple slices managing different parts of the application state (user and posts).

Summary of What We’ve Done:

  1. Created multiple slices (userSlice and postsSlice), each managing a specific part of the application’s state.
  2. Configured a Redux store that combines these slices.
  3. Connected the Redux store to the React application using the Provider component.
  4. Used state and dispatched actions from each slice in a component.

This approach keeps your state management clean and modular by separating concerns into individual slices for each feature or domain in your application.

--

--

No responses yet