Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for reusable calculations on data in redux store

I've just finished wiring up a redux app, and it's fantastic so far. However, because state is stored in a giant store, you don't have any models that you're accessing your data from.

Let's say I have a model class that stores some information about a user. I'd usually add a function to the class called display_name that combines the different parts of their name intelligently. With that, my different views could simply call display_name instead of them needing to know how to calculate it themselves.

Redux explicitly says not to store calculated values in the state, so that leaves it to being defined in the components. This can't possibly be right though, because then you'd end up duplicating this code in every component that needs it.

Where is the proper place to store this logic?

like image 747
Luke Sapan Avatar asked Dec 13 '15 19:12

Luke Sapan


2 Answers

The simplest method is to create utility functions to calculate this data and put them in a separate module that can be used by many components' mapStateToProps functions. A super-simple example:

import { displayName } from "./utils";

function mapStateToProps(state) {
  return {
    displayName: displayName(state.user)
  };
}

function MyComponent(props) {
  return <div>Name: {props.displayName}</div>;
}

export default connect(mapStateToProps)(MyComponent);
like image 107
Michelle Tilley Avatar answered Sep 28 '22 05:09

Michelle Tilley


Per the Computing Derived Data page in the Redux docs, the suggested approach is using the Reselect library for handling selection and memoization.

If you search Github for Javascript projects that contain the term "createSelector", you should find a number of actual apps that are using Reselect in various ways. Here's three that I turned up: jfurrow/flood, FH-Potsdam/shifted maps, and madou/GW2 Armory

like image 34
markerikson Avatar answered Sep 28 '22 06:09

markerikson