Simple mental models for React + (any immutable Flux-like implementation)
I’ve found value in continually simplifying the way that I explain my mental model to others. Especially people coming from a non-FP background (like myself) and struggle to get to the “ah-ha” moment.
State: An immutable object. Most likely a Map.
Store: A container for the state object. Nothing gets direct access to the state object, instead, it asks the Store kindly for the state.
Action: A function which outputs a new state object. Note: It does not mutate state, it returns a new state.
Dispatcher: A function which invokes zero to many actions.
View: A function which renders a view to the user.
Takes two inputs: state & dispatchers.
state: The Store’s current state object.
dispatchers: Functions which are bound to points of user interaction.
Reducer*: A function which “folds/reduces” the return value of an action into what needs to be placed in the store. Flux implementations which use reducers allow actions to return a partial state object which the reducer combines into the whole new state object.
*Reducers may not be present in some Flux implementations or may have a different name in some implementations.
Immutability is compelling because it simplifies how to think about the view layer. It’s a function with two inputs. One input for drawing, the other for interaction. If a user’s interaction changes something, we don’t go about mutating little things all over the screen in a confusingly specific order. Instead, a new state object is created reflecting the user’s change and the view function is invoked afresh.
If a third party, an outside system for example, were to need to be capable of updating data or changing the view? It doesn’t get access to the screen, the store or the system’s state. It gets dispatchers. Functions.
It’s all functions. All the way down.