Redux

A predictable state management library for JavaScript applications, commonly used with React to manage complex application state.

Overview

Redux is a state container that helps you write applications that behave consistently. It centralizes your application's state in a single store and uses a unidirectional data flow pattern. Redux follows three core principles: single source of truth, state is read-only, and changes are made with pure functions (reducers).

Example

javascript
// actions.js
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
export const addTodo = (text) => ({
  type: 'ADD_TODO',
  payload: { text, id: Date.now() }
});

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

function rootReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'ADD_TODO':
      return {
        ...state,
        todos: [...state.todos, action.payload]
      };
    default:
      return state;
  }
}

// store.js
import { createStore } from 'redux';
const store = createStore(rootReducer);

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

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
}

Key Points

  • Centralized state management
  • Predictable state updates
  • Time-travel debugging
  • Works with any framework (popular with React)
  • Modern alternative: Redux Toolkit

Learn More