State Management with Redux

State Management with Redux

Redux is a powerful library used for managing global state in JavaScript applications, especially in React. Redux is particularly useful for larger applications where managing state across many components can become complex.

Introduction to Redux

Redux is based on the principle of a single source of truth, meaning all your application’s state is stored in one central store. The main concepts in Redux are:

  • Store: The global state of the application.

  • Actions: Descriptions of state changes.

  • Reducers: Pure functions that take the current state and an action, then return a new state.

  • Dispatch: A method to send actions to the store.

Setting Up Redux in a React Project

To use Redux in a React project, you’ll need to install the following packages:

npm install redux react-redux

Here’s how you can set up Redux:
1.Create Actions: Actions are plain JavaScript objects that describe the type of state change.

// actions.js
export const increment = () => {
  return {
    type: 'INCREMENT',
  };
};

export const decrement = () => {
  return {
    type: 'DECREMENT',
  };
};

2.Create a Reducer: A reducer is a pure function that takes the current state and an action, then returns a new state.

// reducer.js
const initialState = {
  count: 0,
};

const counterReducer = (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;
  }
};

export default counterReducer;

3.Create the Redux Store: The store holds the global state of the application.

// store.js
import { createStore } from 'redux';
import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;

4.Provide the Store to the React Application: Use the ‘Provider’ component from ‘react-redux’ to make the store available to all components.

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

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

Check it out!