Redux Cheat Sheet

Redux is a state management library commonly used with React applications. Below is a cheat sheet with key concepts and commands used in Redux:

Core Concepts

Store:

  • The single source of truth that holds the entire state of the application.
  • Created using createStore(reducer).

Reducer:

  • A pure function that takes the current state and an action, and returns the new state.
  • Combined using combineReducers().

Actions:

  • Plain JavaScript objects describing the change.
  • Created using action creators.

Action Creators:

  • Functions that create and return action objects.
  • Used to dispatch actions.

Redux Store Creation

import { createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);

Actions and Action Creators

Action Types:

  • Constants representing the type of action.
// Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

Action Creators:

  • Functions that create action objects.
// Action Creators
const increment = () => ({ type: INCREMENT });
const decrement = () => ({ type: DECREMENT });

Reducers

Reducer Function:

  • A pure function that takes the current state and an action, and returns the new state.
// Reducer
const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case INCREMENT:
      return state + 1;
    case DECREMENT:
      return state - 1;
    default:
      return state;
  }
};

export default counterReducer;

Combining Reducers

Combine Reducers:

  • Combine multiple reducers into a single reducer.
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';

const rootReducer = combineReducers({
  counter: counterReducer,
});

export default rootReducer;

Dispatching Actions

Dispatching Actions:

  • Dispatch actions to update the state.
store.dispatch(increment());
store.dispatch(decrement());

Accessing State

Accessing State:

  • Get the current state using getState().
const currentState = store.getState();
console.log(currentState);

Subscribing to Store Changes

Subscribe to Store Changes:

  • Listen for changes in the store.
const unsubscribe = store.subscribe(() => {
  console.log('State updated:', store.getState());
});

// Unsubscribe when needed
unsubscribe();

Middleware

Apply Middleware:

  • Enhance Redux with middleware.
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

Async Actions with Thunk

Thunk Middleware:

  • Allows action creators to return functions.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

// Example async action
const fetchData = () => {
  return (dispatch) => {
    dispatch({ type: 'FETCH_REQUEST' });
    // Async operation (e.g., API call)
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => dispatch({ type: 'FETCH_SUCCESS', payload: data }))
      .catch((error) => dispatch({ type: 'FETCH_FAILURE', payload: error }));
  };
};

store.dispatch(fetchData());

This cheat sheet provides a basic overview of key concepts and commands in Redux. Additional middleware, such as Redux Thunk, can be used for handling asynchronous actions. Explore the official Redux documentation for more in-depth information and advanced use cases.