Redux Toolkit Tutorial - 2 - Getting Started

4 min read 4 hours ago
Published on Nov 05, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial walks you through the process of getting started with Redux Toolkit, a powerful library for managing state in React applications. Redux Toolkit simplifies the process of using Redux by providing a set of tools and best practices. By the end of this guide, you will have a solid foundation to start building your own applications using Redux Toolkit.

Step 1: Setting Up Your Project

To begin using Redux Toolkit, you first need to set up your React project. Follow these steps:

  1. Create a new React application:

    • Open your terminal.
    • Run the following command:
      npx create-react-app my-app
      
    • Replace my-app with your desired project name.
  2. Navigate to your project directory:

    cd my-app
    
  3. Install Redux Toolkit and React-Redux:

    • In the terminal, execute:
      npm install @reduxjs/toolkit react-redux
      

Step 2: Creating the Redux Store

Now that you have the necessary packages, the next step is to create a Redux store.

  1. Create a new directory called app in the src folder:

    • Inside the src folder, create a new folder named app.
  2. Create a file named store.js in the app directory:

    • This file will hold the configuration for your Redux store.
  3. Add the following code to store.js:

    import { configureStore } from '@reduxjs/toolkit';
    import counterReducer from '../features/counter/counterSlice';
    
    export const store = configureStore({
      reducer: {
        counter: counterReducer,
      },
    });
    

Step 3: Setting Up a Slice

A slice is a piece of state along with the reducers and actions associated with it.

  1. Create a new directory called features in the src folder:

    • Inside the src folder, create a folder named features.
  2. Create a new folder called counter inside the features directory:

    • This will contain your counter slice.
  3. Create a file named counterSlice.js in the counter folder:

    • Add the following code to define the slice:
    import { createSlice } from '@reduxjs/toolkit';
    
    export const counterSlice = createSlice({
      name: 'counter',
      initialState: {
        value: 0,
      },
      reducers: {
        increment: (state) => {
          state.value += 1;
        },
        decrement: (state) => {
          state.value -= 1;
        },
        incrementByAmount: (state, action) => {
          state.value += action.payload;
        },
      },
    });
    
    export const { increment, decrement, incrementByAmount } = counterSlice.actions;
    
    export default counterSlice.reducer;
    

Step 4: Integrating Redux Store with React

You now need to connect your Redux store to your React application.

  1. Modify the index.js file:
    • Import the Provider from react-redux and the store you created.
    • Wrap your App component with the Provider:
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Provider } from 'react-redux';
    import { store } from './app/store';
    import App from './App';
    
    ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    );
    

Step 5: Using Redux State in Components

Finally, you can use the state from your Redux store in your components.

  1. Create a new component called Counter.js in the src folder:

    • Add the following code to use the counter slice:
    import React from 'react';
    import { useSelector, useDispatch } from 'react-redux';
    import { increment, decrement } from './features/counter/counterSlice';
    
    function Counter() {
      const count = useSelector((state) => state.counter.value);
      const dispatch = useDispatch();
    
      return (
        <div>
          <h1>{count}</h1>
          <button onClick={() => dispatch(increment())}>Increment</button>
          <button onClick={() => dispatch(decrement())}>Decrement</button>
        </div>
      );
    }
    
    export default Counter;
    
  2. Import and use the Counter component in App.js:

    import React from 'react';
    import Counter from './Counter';
    
    function App() {
      return (
        <div>
          <h1>Redux Toolkit Counter</h1>
          <Counter />
        </div>
      );
    }
    
    export default App;
    

Conclusion

You have now set up a basic Redux Toolkit application with a counter feature. You learned how to create a Redux store, set up a slice, and connect the store to your React components.

Next Steps

  • Explore more advanced features of Redux Toolkit, such as asynchronous actions using createAsyncThunk.
  • Consider adding more slices to manage different pieces of state in your application.
  • Experiment with middleware for logging, handling side effects, or integrating APIs.