This is not a React specific question. I'm thinking of implementing Flux in Aurelia/Angularjs.
While reading up on flux, I'm not convinced of the need of the dispatcher step. Why can't a component call the store directly to update and retrieve data? Is there anything wrong with that approach?
For example: If I have a CarStore
that can create new cars, update cars and get a list of cars(just a thin layer on the CRUD api), I should be able to retrieve/update the list by directly calling the store from the car-grid
component. Since the store is a singleton, whenever the list updates, car-grid
should automatically get the new items. What is the benefit of using a dispatcher in this scenario?
Dispatcher is used to broadcast payloads to registered callbacks. This is different from generic pub-sub systems in two ways: Callbacks are not subscribed to particular events. Every payload is dispatched to every registered callback.
The dispatch function is the exact same function as React returned for the previous call to useReducer. The component sets up an event handler. This is a new version of the handler and may use some of the newly updated state values. The component returns its UI.
Actions − Actions are sent to the dispatcher to trigger the data flow. Dispatcher − This is a central hub of the app. All the data is dispatched and sent to the stores. Store − Store is the place where the application state and logic are held.
Flux applications have three major parts: the dispatcher, the stores, and the views (React components). These should not be confused with Model-View-Controller.
I've created several large apps using React-native with Redux as the store / view state updater.
The dispatch action is synchronous regardless. There's a big disadvantage to using dispatchers, you lose the function signature. (Debugging, auto-catching type-errors, refactoring lost, multiple declarations of the same function, list goes on)
Never had to use a dispatcher and its caused no issues. Within the actions we simply call getState().dispatch. The store is a singleton anyhow, it's heavily recommended you don't have multiple stores. (Why would you do that...)
You can see here why are dispatchers important (check out the section Why We Need a Dispatcher). The way I see it, the idea is basically being able to access to various stores in a synchronous way (one callback finishes before another one is called). You can make this thanks to the waitFor
method, which allows you to wait for a store to finish processing an action (or more tan one). There is a good example in the docs. For example, your application may grow and instead of having just that CarStore you have another Store whose updates depend on the CarStore updates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With