Redux is a predictable state container for JavaScript applications. It helps you write applications that behave consistently, run in different environments, and are easy to test. Redux is commonly used with React but can work with any JavaScript framework or library.

Core Principles

  1. Single Source of Truth: The global state is stored in a single store
  2. State is Read-Only: State can only be changed by dispatching actions
  3. Changes Made with Pure Functions: Reducers are pure functions that specify how state changes

Key Concepts

  • Store: Holds the complete state tree of your application
  • Actions: Plain objects that describe what happened
  • Reducers: Pure functions that take state and action, return new state
  • Dispatch: Method to send actions to the store
  • Selectors: Functions to extract specific data from state
  • Middleware: Extends Redux with custom functionality

Basic Example

// Action
const increment = () => ({
  type: 'INCREMENT'
});

// Reducer
const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    default:
      return state;
  }
};

// Store
import { createStore } from 'redux';
const store = createStore(counterReducer);

// Usage
store.dispatch(increment());
console.log(store.getState()); // { count: 1 }
                    

Redux with React

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

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

  return (
    <div>
      <span>{count}</span>
      <button onClick={() => dispatch(increment())}>
        +
      </button>
    </div>
  );
}
                    

Benefits

  • Predictability: State mutations are predictable and traceable
  • Debugging: Time-travel debugging with Redux DevTools
  • Testing: Easy to test pure functions and isolated components
  • Server Rendering: State can be serialized and hydrated
  • Developer Experience: Hot reloading and time travel debugging

When to Use Redux

  • Large applications with complex state management needs
  • State needs to be shared across many components
  • State updates follow complex logic
  • Medium to large codebase with many developers
  • Need for time-travel debugging capabilities

Learning Path

  1. JavaScript Fundamentals: ES6+, functions, objects
  2. React Basics: Components, props, state, hooks
  3. Redux Core: Actions, reducers, store
  4. React-Redux: connect, useSelector, useDispatch
  5. Middleware: Redux Thunk, Redux Saga
  6. Redux Toolkit: Modern Redux development
  7. Advanced Patterns: Normalization, selectors