eguneys eguneys - 1 month ago 11
React JSX Question

How to setup Ember like computed properties in Immutablejs and Redux and Flux and React

I am used to computed properties in Ember Object Model. It's a convenient way to specify computed properties that depend on other properties.

Say

fullName
depends on
firstName
and
lastName
, I can setup computed properties as a function
computeProperties
and call
computeProperties
each time I make a change.

Example:

function computeFullName(state) {
const fullName = state.get('firstName') + state.get('lastName');
const nextState = state.set('fullName', fullName);
return nextState;
}

function computeProperties(state) {
const nextState = computeFullName(state);
return nextState;
}

// store action handler
[handleActionX](state) {

let nextState = state.set('firstName', 'John');
nextState = state.set('lastName', 'Doe');

nextState = computeProperties(nextState);

return nextState;
}


Is there a way to automatically setup computed properties so that I don't have to call extra functions each time. In Redux or in ImmutableJS.

Answer

Redux author here.

Using reselect as suggested by WildService is the way to go. I think we won't include this in core because reselect does its job well, and we're fine with it being a separate library.

I wanted to note a couple of things:

  • Even with reselect, you don't want to compute data inside your reducer. Selectors should operate on the state managed by reducers. In other words, selectors are the step between your Redux store state and your components—they are not inside your reducers. It is essential you keep Redux state normalized so it's easy to update.

  • We actually encourage you to define selectors alongside the relevant reducers, so that when you change the state shape, you don't have to change your components—they would be using the selectors instead. You can see an example of this in the Redux folder of Flux Comparison

  • We have a documentation page introducing reselect and describing how to use it for computing derived data. Check it out.