Home  Reactjs   How to crea ...

How to create multiple slices using Redux toolkit

You can create multiple slices in Redux using Redux Toolkit. Each slice is responsible for a specific piece of the state and contains its own actions and reducers. This modular approach helps keep your Redux logic organized and maintainable, especially as your application grows.

Creating Multiple Slices

To create multiple slices, you define each slice using createSlice and then combine them in the store using configureStore.

Example: Let's create a simple Redux setup with two slices: one for managing user state and another for managing posts state.

User Slice

// userSlice.js
import { createSlice } from '@reduxjs/toolkit';

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

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUser: (state, action) => {
      state.name = action.payload.name;
      state.email = action.payload.email;
    },
    clearUser: (state) => {
      state.name = '';
      state.email = '';
    }
  }
});

export const { setUser, clearUser } = userSlice.actions;
export default userSlice.reducer;

Posts Slice

// postsSlice.js
import { createSlice } from '@reduxjs/toolkit';

const initialState = [];

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {
    addPost: (state, action) => {
      state.push(action.payload);
    },
    removePost: (state, action) => {
      return state.filter(post => post.id !== action.payload.id);
    }
  }
});

export const { addPost, removePost } = postsSlice.actions;
export default postsSlice.reducer;

Configuring the Store

You can combine these slices using configureStore.

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

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

export default store;

Using the Store in a React Component

You can use these slices in your React components with the useDispatch and useSelector hooks from react-redux.

Example:

// App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setUser, clearUser } from './userSlice';
import { addPost, removePost } from './postsSlice';

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

  const handleAddUser = () => {
    dispatch(setUser({ name: 'John Doe', email: '[email protected]' }));
  };

  const handleClearUser = () => {
    dispatch(clearUser());
  };

  const handleAddPost = () => {
    dispatch(addPost({ id: 1, title: 'First Post', content: 'Hello world!' }));
  };

  const handleRemovePost = () => {
    dispatch(removePost({ id: 1 }));
  };

  return (
    <div>
      <div>
        <h2>User</h2>
        <p>Name: {user.name}</p>
        <p>Email: {user.email}</p>
        <button onClick={handleAddUser}>Add User</button>
        <button onClick={handleClearUser}>Clear User</button>
      </div>
      <div>
        <h2>Posts</h2>
        <ul>
          {posts.map((post) => (
            <li key={post.id}>
              <h3>{post.title}</h3>
              <p>{post.content}</p>
              <button onClick={() => handleRemovePost(post.id)}>Remove Post</button>
            </li>
          ))}
        </ul>
        <button onClick={handleAddPost}>Add Post</button>
      </div>
    </div>
  );
};

export default App;
Published on: Jul 21, 2024, 11:41 AM  
 

Comments

Add your comment