DEV Community

bilal khan
bilal khan

Posted on

Getting Started with Redux

A Brief Example with Explanation

Redux is a powerful state management tool that helps you manage your application’s state predictably. If you’re new to Redux, this guide will walk you through a simple example to understand its basics and how it integrates with React.


Scenario: A Counter Application

We’ll create a simple counter app that lets users increment and decrement a value. This example will demonstrate how to set up Redux, define state and actions, and connect everything to a React app.


Step 1: Setting Up Redux

Install the required libraries:

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

Step 2: Create a Redux Slice

Redux Toolkit simplifies Redux by combining actions and reducers into slices. Here’s how to create one for our counter app:

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

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => {
      state.value += 1; // Directly modify state using Immer
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • createSlice: Simplifies Redux by bundling actions and reducers.
  • initialState: Sets the starting value for the counter.
  • reducers: Functions defining how state changes in response to actions.

Step 3: Configure the Store

The store holds the global state of your app.

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

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The configureStore function combines reducers and sets up the Redux store.
  • Our app’s state is managed by the counterReducer.

Step 4: Provide the Store to Your App

Wrap your app with the Provider component from React-Redux.

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')
);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Provider makes the Redux store available to all React components.

Step 5: Access State and Dispatch Actions

Use the useSelector and useDispatch hooks to interact with Redux in your components.

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

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

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>
        Increment by 5
      </button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useSelector: Accesses the state (state.counter.value).
  • useDispatch: Sends actions (e.g., increment, decrement) to update the state.

Step 6: See It in Action

Now run your app:

npm start
Enter fullscreen mode Exit fullscreen mode

You’ll see the counter app with buttons to increment, decrement, and increment by a specific amount.


How It Works

  1. Global State Management: Redux maintains a single source of truth for your app’s state.
  2. Unidirectional Flow: State updates follow a strict flow:
    • Dispatch an action → Reducer updates state → Component reflects changes.
  3. Simplified with Toolkit: Redux Toolkit eliminates boilerplate, making it easier to define and manage state.

Conclusion

In this example, we covered:

  • Setting up Redux using Redux Toolkit.
  • Creating a slice with actions and a reducer.
  • Configuring a store and integrating it with React.

Redux simplifies state management, especially in apps with complex or shared state. Start small, and as your app grows, you’ll see how Redux helps maintain structure and scalability.

For more advanced concepts like middleware and async actions, stay tuned for future posts!

Top comments (0)