Blog>
Snippets

Reducer Optimizations for High Velocity Data

Demonstrate performance optimizations in a reducer that processes a stream of stock market price updates using `createReducer`.
import { createReducer } from '@reduxjs/toolkit';
import { createSelector } from 'reselect';
import produce from 'immer';

// Initial state for the stock market prices
const initialState = { prices: {} };

// Reducer using createReducer and Immer for handling high-velocity stock price updates
const stockPriceReducer = createReducer(initialState, {
    updatePrice: (state, action) => {
        const { stockId, newPrice } = action.payload;
        state.prices[stockId] = newPrice;
        // Immer makes the state mutation safe
    }
});

// Selector to get a specific stock price
const selectStockPrice = createSelector(
    state => state.prices,
    (_, stockId) => stockId,
    (prices, stockId) => prices[stockId]
);

// Usage of the selector within a component
// const stockPrice = useSelector(state => selectStockPrice(state, 'AAPL'));
This code sets up a Redux reducer that handles high-frequency stock market price updates. It utilizes Redux Toolkit's createReducer function alongside Immer for safe state mutation, and reselect's createSelector for memoized selectors to efficiently retrieve stock prices without unnecessary recalculations.