Reputation: 495
Why react-redux passes the store to the React's context using Provider behind the scene as we can dispatch using store.disptach and get the state using store.getState, so basically all the functionalities can be achieved without using React.createContext. Am I missing something here? or are there some other advantages of doing so?
Thank you
Upvotes: 2
Views: 231
Reputation: 67607
React's Context API is effectively a lightweight Dependency Injection system. Like any DI system, the value is in avoiding binding your logic to a specific instance or implementation at compile time.
For React-Redux specifically, there's many portions of Redux-connected logic that need to talk to some Redux store instance at runtime, but we don't know which Redux store instance that will be at the time we write the code. For example:
So, passing down the store via context allows us to write components that interact with a store, but we don't care which store it is. That gets injected at runtime.
In general, do not import the Redux store directly into your components (or other files): https://redux.js.org/style-guide/style-guide#only-one-redux-store-per-app
Upvotes: 5