DEV Community

Leo Kalshteyn
Leo Kalshteyn

Posted on

Redux Providers

Every component usually needs access to the Redux store. Passing it as props in every component could get tiresome, but there is a feature that simplifies this. This cool feature of React Redux that I recently read about is called the Provider. The provider gives access to the Redux store for any nested components that provider wraps in the connect function.

You only need to use it once when you render the root component, so usually, it is done by rending it with the entire app's component tree inside of it.

Example:

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'

import { App } from './App'
import createStore from './createReduxStore'

const store = createStore()

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
Enter fullscreen mode Exit fullscreen mode

Or with React Router where you import other components:

import { Router, Route } from 'react-router-dom'

import { App } from './App'
import { Foo } from './Foo'
import { Bar } from './Bar'
import createStore from './createReduxStore'

const store = createStore()

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route exact path="/" component={App} />
      <Route path="/foo" component={Foo} />
      <Route path="/bar" component={Bar} />
    </Router>
  </Provider>,
  document.getElementById('root')
Enter fullscreen mode Exit fullscreen mode

Some things to note

If a context instance is provided, the same context instance is required in all the connected components or a runtime error will appear:

Could not find "store" in the context of "Connect(MyComponent)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(Todo) in connect options.

Also, it is not necessary to provide a custom context to access the store as React Redux exports the context instance in use by default.

import { ReactReduxContext } from 'react-redux'

// in your connected component
render() {
  return (
    <ReactReduxContext.Consumer>
      {({ store }) => {
        // do something with the store here
      }}
    </ReactReduxContext.Consumer>
  )
}
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)