Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use "this.props.dispatch" rather than "store.dispatch" directly in Redux?

Tags:

reactjs

redux

Is there any detriment to directly using store.dispatch?

It seems to me it's much easier to call (since it's available to all child components) and in my testing so far, I've yet to find a difference.

Thanks!

like image 303
user1543574 Avatar asked Oct 19 '15 18:10

user1543574


People also ask

Why dispatch is used in Redux?

dispatch() is the method used to dispatch actions and trigger state changes to the store. react-redux is simply trying to give you convenient access to it. Note, however, that dispatch is not available on props if you do pass in actions to your connect function.

What happens when we dispatch an action in Redux?

Redux uses a "one-way data flow" app structure When something happens in the app: The UI dispatches an action. The store runs the reducers, and the state is updated based on what occurred. The store notifies the UI that the state has changed.

Who is responsible for dispatching the action in Redux?

A Redux app really only has one reducer function: the "root reducer" function that you will pass to createStore later on. That one root reducer function is responsible for handling all of the actions that are dispatched, and calculating what the entire new state result should be every time.

How do I use the dispatch in Redux?

Redux doesn't have a Dispatcher or support many stores. Instead, there is just a single store with a single root reducing function. As your app grows, instead of adding stores, you split the root reducer into smaller reducers independently operating on the different parts of the state tree.


2 Answers

In universal apps, you'll want a different store instance on every request. If you just export store as a singleton from some module, you'll have a hard time adding server rendering.

This is why we never encourage singleton store in the docs, and always encourage you to use <Provider> to pass it down the hierarchy via React context. This makes store available to the consuming components without making it a singleton.

As for why connect() from React Redux passes dispatch as a prop instead of store itself—it's because you don't really need store itself in the connected components. Subscription and reading state is done by connect() so you'll only ever need dispatch() in components.

like image 187
Dan Abramov Avatar answered Sep 21 '22 13:09

Dan Abramov


Usually I find that the store is initialized in a top level module, and then used in lower level modules by the react-redux connect function.

This prevents the need to import the store directly in a lower level module, as it would be importing from the top level.

like image 20
J3Y Avatar answered Sep 21 '22 13:09

J3Y