DEV Community

Cover image for Redux : State Management Tool
Achal Tiwari
Achal Tiwari

Posted on

Redux : State Management Tool

Hello! Today, we are going to explore how to manage state in production-ready projects using Redux. For those who aren't familiar with state management, let's break it down.

What is State Management?

State management is about handling the state of various user interface elements, such as text fields, buttons, and other interactive components in a graphical user interface. To get a clearer understanding of state management and React, check out the Context API. You can read the official docs or my article on it.

What is Redux?

Redux is a pattern and library for managing and updating application state, using events called "actions".

  • It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.
Key Concepts of Redux

Store: The store holds the state of your application.
Actions: Actions are plain JavaScript objects that describe what happened.
Reducers: Reducers specify how the application's state changes in response to actions.

Image description

Setting Up Redux in a React App

Let's start by setting up Redux in a simple React app.

npx create-react-app my-redux-app
cd my-redux-app
npm install redux react-redux
Enter fullscreen mode Exit fullscreen mode

Set Up the Redux Store

Create a store.js file:

import { createStore } from 'redux';
// Initial state
const initialState = {
  count: 0,
};
// Reducer
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

// Create store
const store = createStore(reducer);

export default store;
Enter fullscreen mode Exit fullscreen mode

Provide the Store to Your App

Wrap your app with the Provider component from react-redux in index.js:

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

ReactDOM.render(
// this wrap helps all your components to get access of your store
  <Provider store={store}> 
    <App />
  </Provider>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Connect Components to Redux

Create a Counter.js component:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
//Selector helps you to get access of data based on provided state
  const count = useSelector(state => state.count); 
// useDispatch allows React components to dispatch actions to the // Redux store.
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Count: {count}</h1>
// we have made switch cases based on action type, therefore we 
// need to pass type along with dispatch
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Add the Counter component to your App.js:

import React from 'react';
import Counter from './Counter';

function App() {
  return (
    <div className="App">
      <Counter />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now, this approach is a bit complex, but it's essential to understand the fundamentals of Redux and how it works. In the second part, we'll simplify things by using redux-toolkit. Let's dive into the easier way of managing state with Redux Toolkit!

1. Install Redux Toolkit

npm install @reduxjs/toolkit
Enter fullscreen mode Exit fullscreen mode

2. Set up the store with Redux Toolkit

Update your store.js file

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

//A slice is a collection of actions and reducer logic for a single feature in an app

// Create a slice
const counterSlice = createSlice({
  name: 'counter',
  initialState: { count: 0 },
  reducers: {
    increment: state => { state.count += 1; },
    decrement: state => { state.count -= 1; },
  },
});

// Export actions
export const { increment, decrement } = counterSlice.actions;

// Create store
const store = configureStore({
  reducer: counterSlice.reducer,
});

export default store;
Enter fullscreen mode Exit fullscreen mode

3. Update the Component

Update the Counter.js

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

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

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

export default Counter;
Enter fullscreen mode Exit fullscreen mode

This is it, you are done, now go and make real world application to have practice with redux. Happy Coding!

Top comments (0)