20 Feb 2024




Intermediate

Redux is a predictable state container for JavaScript applications. It helps manage the state of your application in a predictable way and makes it easier to understand and debug your application's state changes. Redux follows a unidirectional data flow, and its core concepts include State, Actions, Reducers, and the Store.

  1. State:

    • The state represents the current state of your application. It is a plain JavaScript object that holds the data you want to manage. In Redux, the state is typically stored as a single immutable object.
  2. Actions:

    • Actions are plain JavaScript objects that describe events in your application. They are the only way to send data to the Redux store. An action must have a type property that describes the type of action being performed, and it may also include additional data (payload).
    // Example action
    const increment = {
      type: 'INCREMENT',
      payload: 1,
    };
    
  3. Reducers:

    • Reducers are pure functions that take the current state and an action as arguments and return a new state. Reducers specify how the application's state changes in response to actions. They should not modify the existing state but rather return a new state based on the provided state and action.
    // Example reducer
    const counterReducer = (state = 0, action) => {
      switch (action.type) {
        case 'INCREMENT':
          return state + action.payload;
        case 'DECREMENT':
          return state - action.payload;
        default:
          return state;
      }
    };
    
  4. Store:

    • The store is the core of Redux and holds the application state. It is created by passing a reducer function to the createStore function from the Redux library. The store has methods to dispatch actions, subscribe to state changes, and get the current state.
    import { createStore } from 'redux';
    
    const store = createStore(counterReducer);
    

    With these concepts, the flow in a Redux application typically looks like this:

    1. Something happens in the application (e.g., a user clicks a button).
    2. An action is dispatched to the Redux store.
    3. The reducer processes the action and returns a new state.
    4. The store updates its state.
    5. Components that are subscribed to the store re-render based on the updated state.

This unidirectional flow makes it easier to track and understand how the state changes in your application.