I have a module object, that consists of several parameters and an algorithm.
A parameter consists of a min
, max
, step
, label
and value
.
The module’s algorithm is regularly making a calculation based on a value on each the parameters.
In my application each of the parameters is represented by a slider on the GUI.
If you’re interested, the production version of this application is here. The code base is a mess and I’m currently tidying up.
My question is how I represent this in a react/redux architecture.
The module and its algorithm are static. But a user should be able to save the state of the application, which will likely be saved on a JSON database. At the minimum all this needs to be is simple JSON object that contains the value of each of the parameters.
So what I want to be able to do is, for each of modules, list a series of parameters that define the algorithm, and the react just for each renders each of the parameters. Simple enough.
How do I handle the differentiation between the functional model, the state we’re trying to save, which is just a few values? Should I be using my doing the algorithmic calculations as a part of the dispatch actions? Does this list of parameters come through from the redux state?
This sounds like a good use case for the Reselect helper library.
You want to keep your Redux state (and, by extension, the reducers) as simple as possible, so only include the input parameters for the calculation.
Then implement your algorithm as one or more selectors – pure functions that take the Redux state as an input and return the calculated values.
Reselect provides a method called createSelector
which will automatically memoize your function – i.e. it caches the last set of input values and the result. If your selector is called again with the same inputs, then it just returns the cached result instead of repeating the calculation.
Selectors are composable – you can use the output of one selector as the input for another. Thus, by using selectors to pick out the relevant properties of the state, you can ensure that the main calculation is not repeated unnecessarily when other parts of the state are changed.
Finally, when you connect your React component to Redux, call the selectors from mapStateToProps()
:
function mapStateToProps(state) {
return {
fooProp: myFooSelector(state),
barProp: myBarSelector(state)
};
}
This means that the selectors get called on every render – which is OK, since they don’t do any work unless the relevant state properties have changed.
The view is now guaranteed to stay in sync with the input values, and you don’t even have to think about the circumstances when the results might change.
Even better, the algorithm is lazily evaluated – the calculation doesn’t even happen unless the user looks at a page which requires it.
0