Kartik Malik
Kartik Malik

Reputation: 495

Why react-redux passes store to context?

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

Answers (1)

markerikson
markerikson

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:

  • Your application components may use a known singleton store instance in the real application, but you need to create a unique store instance on the fly for every unit test: https://redux.js.org/recipes/writing-tests#connected-components
  • You may be publishing Redux-connected components as a library, and those certainly cannot know which Redux store a user will be using

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

Related Questions