Computed properties

Where Ember Data encourages one to store derived data (i.e. computed properties) on a model instance, Redux encourages you to use a simple function of your component's state and props called a selector. Selectors can also compute derived data from our state tree, and like computed properties, are not recomputed unless its arguments change.

Where with Ember Data, we might describe a computed property at the model level:

// ember-models
export const displayTitle = computed('title', function() {
  return get(this, 'title') || DEFAULT_CARD_TITLE;
});

// component
get(model, 'displayTitle');

// template
<div>{{ displayTitle }}</div>

…the Redux equivalent with selectors would have us describe it as function of the state and props passed to the component you're connecting to the Redux store:

// selector
export function getDisplayTitle(state, props) {
  return props.title || DEFAULT_CARD_TITLE;
};

// component
const stateMap = (state, props) => {
  displayTitle: getDisplayTitle(state, props)
};
const titleComponent = Ember.Component.extend(…);
export default connect(stateMap)(titleComponent);

// template
<div>{{ displayTitle }}</div>

That looks like more code I have to write...

Selectors compose and so are pretty reusable. And since they are simple functions that return primitive data, they are also easy to test. There will be an upfront cost to building out the most basic and commonly used selectors which will make it seem like you have to write more code at first, but soon we'll be in a world where your component will already be connected to Redux, and maybe that selector you're looking for is already written.

Notably, computed properties are coupled to the object they are declared on and can't easily be reused outside of that object. We have cases where identical computed properties are declared on multiple objects. With selectors, these can be declared once and centralized where appropriate.

How is this different than computed properties?

They are conceptually similar! Computed properties are really great, but aren't idiomatic to the Redux ecosystem. They tend to store and mutate non-enumerable data on the model objects observed in the system, which violates the second rule of Redux, which is that outside of a reducer, state is read-only.

How does this work with normalized-get?

[something to the effect of, use nget at the route level, send as prop to connected container component, use selectors from there, show example]…

More examples

results matching ""

    No results matching ""