How to Implement Redux Reducers in React

This article provides a straightforward guide on how to implement Redux reducers in a React application. You will learn the core concept of a reducer, how to create one using Redux Toolkit, and how to connect it to your React components to manage global state efficiently.

What is a Redux Reducer?

A Redux reducer is a pure function that determines changes to an application’s state. It receives the current state and an action object, then returns a new state based on the action type. Reducers must be pure; they should never modify the existing state directly, but rather return a new state object.

Step 1: Install Required Packages

To use Redux in React, you need the official Redux Toolkit and React-Redux binding library. Run the following command in your terminal:

npm install @reduxjs/toolkit react-redux

Step 2: Create a Reducer Slice

Redux Toolkit simplifies state management using “slices.” A slice automatically generates action creators and reducers for you.

Create a file named counterSlice.js:

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

const initialState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library.
      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 3: Configure the Redux Store

Next, you need to create the Redux store and pass in the reducer you just created.

Create a file named store.js:

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

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

Step 4: Provide the Store to React

To make the Redux store available to your entire React component tree, wrap your root component with the Provider component from react-redux.

In your main.jsx or index.js file:

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

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

Step 5: Use Redux State and Actions in Components

Now you can read state from the store using the useSelector hook and dispatch actions using the useDispatch hook.

In your App.jsx component:

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

function App() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1>Counter: {count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())} style={{ margin: '0 10px' }}>Decrement</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>Increment by 5</button>
    </div>
  );
}

export default App;