Skip to content

Scoped Actions and Reducers

Laura buns edited this page Feb 14, 2019 · 1 revision

The main reason for having shared components is to reduce the amount of duplication in the codebase. If we have the same piece of UI across multiple pages, we should be able to reuse the same code. However, if we were only able to share the bare component, and had to rewrite the corresponding reducers and actions for every new instance, we wouldn't really be getting much benefit. We want to share these auxiliary constructs too! However, this results in a potentional problem...

The Problem

For a component to be truly shared, it should be possible to use it multiple times in the same page. Now, it's fairly straightforward to reuse a reducer multiple times in the same store, as you can just drop it into different compartments in the state:

import { combineReducers } from 'redux';

import reusableReducer from './reusableReducer';

const appReducer = combineReducers({
  sectionOne: reusableReducer,
  sectionTwo: reusableReducer,
  sectionThree: reusableReducer,
});

However, this results in a problem. While reducers can be compartmentalised in this way, actions are global in the Redux store. This means that whenever an action that corresponds to reusableReducer is fired, all the places in the state that use that reducer are updated. This is probably not what you want, because, for example, clicking on a reusable checkbox in a given page may end up checking every other checkbox on that page.

The Solution(s)

Fortunately, this topic is covered in the Redux docs, and there are a couple of different solutions offered. We use the second because it allows us to maintain type safety for our actions. In brief, this method involves using action creator and reducer factories, into which you pass the scope (as a string) and get back scoped actions creators and reducers. To see how this works, have a look at contributionSelectionReducer and contributionSelectionActions. There's a great article by AppNexus where they describe setting things up in this way.

πŸ™‹β€β™€οΈ General Information

🎨 Client-side 101

βš›οΈ React+Redux

πŸ’° Payment methods

πŸŽ› Deployment & Testing

πŸ“Š AB Testing

🚧 Helper Components

πŸ“š Other Reference

1️⃣ Quickstarts

πŸ›€οΈ Tracking

Clone this wiki locally