DEV Community

Cover image for Redux with React: A Friendly Guide for Beginners
Sarvesh S. Kulkarni
Sarvesh S. Kulkarni

Posted on

Redux with React: A Friendly Guide for Beginners

Hey there! 🎉 If you’ve been diving into React and are ready to level up your state management game, you’ve probably heard of Redux. It’s a powerful tool that helps you handle state in a predictable and organized way, especially as your app grows bigger. Don’t worry if Redux sounds a bit daunting right now—this guide will break it down step-by-step in a super casual, easy-to-follow way. Let’s get started!

What’s Redux All About?
Imagine your React app as a big, busy kitchen. You have ingredients (state) that need to be organized and used in recipes (components). Redux acts like a super-efficient kitchen organizer. It keeps all your ingredients (state) in one place (the store), and whenever you need to make a recipe (update the state), it tells you exactly how to do it (reducers).

Redux Basics

1. Store: Think of this as your pantry where you keep all your ingredients (state).
2. Actions: These are like recipe instructions. They tell the store what you want to do (e.g., "Add sugar").
3. Reducers: They’re the chefs who take the recipe (action) and update the pantry (store) accordingly.
4. Dispatch: This is how you get the recipe instructions to the chefs (reducers).

Setting Up Your Project
Let’s set up a React project with Redux. It’s super easy with create-react-app—a handy tool that gets everything ready for you.

1. Create Your React App
Open up your terminal and run these commands to start a new project:

npx create-react-app redux-tutorial
cd redux-tutorial
Enter fullscreen mode Exit fullscreen mode

2. Add React-Redux and @reduxjs/toolkit
Now, let’s install React-Redux and @reduxjs/toolkit, which helps connect Redux with React.

npm install react-redux @reduxjs/toolkit
Enter fullscreen mode Exit fullscreen mode

Using createSlice to Manage State
We’ll use createSlice to set up our Redux store. It lets us define our state, actions, and reducers all in one place.

1. Create a Slice
Let’s create a counterSlice.tsx file in a new features folder. This file will manage our counter state.

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
    },
  },
})

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer
Enter fullscreen mode Exit fullscreen mode

2. Configure the Store
Create a store.ts file to configure the Redux store using the slice we just created.

import { configureStore } from '@reduxjs/toolkit'
import counterSlice from '../feature/counterSlice'

export default configureStore({
  reducer: {
    counter: counterSlice, 
  },
})
Enter fullscreen mode Exit fullscreen mode

3. Provide the Redux Store to React
Wrap your app with the Provider component so that Redux can manage the state. Update index.tsx like this:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";
import store from './app/store'
import { Provider } from 'react-redux'
import Navbar from './components/Navbar';
import Footer from './components/Footer';

const router = createBrowserRouter([
  {
    path: "/",
    element: <App/>,
  },
  {
    path: "*",
    element: <div className='d-flex justify-content-center align-items-center m-5'>Not Found</div>,
  }
]);

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
      <Navbar/>
        <Provider store={store}>
        <RouterProvider router={router}/>
        </Provider>
      <Footer/>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Enter fullscreen mode Exit fullscreen mode

4. Connect Your Component to Redux
Now, let’s connect a React component to the Redux store using useSelector and useDispatch from react-redux. Create a Counter.tsx component:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '../feature/counterSlice';

// Define the types for your state
interface CounterState {
  value: number;
}

interface RootState {
  counter: CounterState;
}

export function Counter() {
  // Use useSelector to access the counter and food items from the state
  const count = useSelector((state: RootState) => state.counter.value);

  const dispatch = useDispatch();

  return (
    <div>
      <fieldset className='border m-5'>
        <legend className='text-center'>Basic Counter</legend>
        <div  className='d-flex justify-content-center align-items-center'>
        <button
          aria-label="Increment value"
          className='btn btn-outline-success'
          onClick={() => dispatch(increment())}
        >
          Increment
        </button>
        <span className='p-5 fs-5 fw-semibold text-secondary'>{count}</span>
        <button
          aria-label="Decrement value"
          className='btn btn-outline-danger'
          onClick={() => dispatch(decrement())}
        >
          Decrement
        </button>
      </div>
      </fieldset>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Update App.tsx to include the Counter component:

import './App.css';
import { Counter } from './components/Counter';

function App() {

  return (
    <>
    <Counter/>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Wrapping Up
You’ve just set up Redux in your React app using Redux Toolkit and createSlice. Here’s a quick rundown of what we did:

  • Setup: Created a new React project and installed Redux Toolkit.
  • Slice: Defined our state and reducers in one place using createSlice.
  • Store: Configured the store with the slice’s reducer.
  • Provider: Wrapped our app with the Redux Provider.
  • Component: Connected a React component to the Redux store with useSelector and useDispatch.

I have implemented the example of the multi-state management in the this repository.

Please feel free to explore the code, and if you have any questions or suggestions, don’t hesitate to open an issue or submit a pull request. Your feedback is always appreciated!

Redux Toolkit makes it super easy to manage state in a scalable and maintainable way. Enjoy building your app, and have fun with Redux Toolkit! 🚀

Top comments (2)

Collapse
 
javav profile image
Javav

whats redux

Collapse
 
sarveshk76 profile image
Sarvesh S. Kulkarni

It's an open-source JS library for managing and centralizing application state.