Idea
Both have the same origin. The idea consists of:
“The resultant state of the application is the application of its event history to a clean initial state.”
This is what our old reduce function does:
reducer :: ((B, A) -> B) -> B -> T A -> B
OBS: This is a modified signature to met the javascript. The way Haskell implements is “foldl :: (b -> a -> b) -> b -> t a -> b“
Having a initial state B, we can apply all the events that a container T A has (in typescript it could be something like A[] where T is the [] - any container), and, in the end, we have the resultant state. (B, A) -> B is the reduction function. It’s the function that knows how to combine each event to the state.
In javascript if would be like:
[eventA, eventB].reducer(
(currentState, event) => currentState + event,
state
)
How does it work?
It’s just a “loop”:
The reducer provides a pair of [state, dispatcherFunction].
The state at some time and a dispatcher function that, once called, it trigger the rebuild of the react components’ tree.
You can make a stateful dispatch function pretty easily.
let rendered, state;
function render() {
function dispatcher(event) {
state = reducer(state, event)
render();
}
rendered = vdom_patch(rendered, app(state, dispatcher));
}
The UI event handler dispatches an event that will be combined and stored for the next rendering.
A difference from using useReducer and Redux is that Redux has the same problem of many javascript libraries - it only deals with primitive types.
Redux “bad practice”
It’s common to view an application as a hierarchy of components creating levels. It’s a difficult to avoid mental model.
This way we have to pass the state on each level of the tree, so that all the components have access to it.
This is what people call property drilling.
Contrary to what people say, there is no problem with that. The information must flow somehow. Property drilling is even better than what people recommend to connect every component directly to the store, or get the most stateful labrary.
ViewController (nothing new here)
This component is responsible for managing the state, passing state to other components, and provides functionality for them.
It’s one strategy to deal with coupling simple components and state.
For convenience, using redux, we can connect a store to this component, and, it will respond to the route.
Page is just any layout. It just knows how to place items in their right place.
Components that would be hidden inside the page, we bring them close to the state.
This way, we can manage independent components of the store, and it will also improve the way we write our tests by reducing the amount of dependencies (and terrible mocks).