|
| 1 | +# `<Provider />` |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +The `<Provider />` makes the Redux `store` available to any nested components that have been wrapped in the `connect()` function. |
| 6 | + |
| 7 | +Since any React component in a React-Redux app can be connected, most applications will render a `<Provider>` at the top level, with the entire app’s component tree inside of it. |
| 8 | + |
| 9 | +Normally, you can’t use a connected component unless it is nested inside of a `<Provider>` . |
| 10 | + |
| 11 | +Note: If you really need to, you can manually pass `store` as a prop to a connected component, but we only recommend to do this for stubbing `store` in unit tests, or in non-fully-React codebases. Normally, you should just use `<Provider>`. |
| 12 | + |
| 13 | +### Props |
| 14 | + |
| 15 | +`store` (Redux Store) |
| 16 | +The single Redux `store` in your application. |
| 17 | + |
| 18 | +`children` (ReactElement) |
| 19 | +The root of your component hierarchy. |
| 20 | + |
| 21 | + |
| 22 | +### Example Usage |
| 23 | + |
| 24 | +In the example below, the `<App />` component is our root-level component. This means it’s at the very top of our component hierarchy. |
| 25 | + |
| 26 | +**Vanilla React Example** |
| 27 | + |
| 28 | +```js |
| 29 | + import React from 'react'; |
| 30 | + import ReactDOM from 'react-dom'; |
| 31 | + import { Provider } from 'react-redux'; |
| 32 | + |
| 33 | + import { App } from './App'; |
| 34 | + import createStore from './createReduxStore'; |
| 35 | + |
| 36 | + const store = createStore(); |
| 37 | + |
| 38 | + ReactDOM.render( |
| 39 | + <Provider store={store}> |
| 40 | + <App /> |
| 41 | + </Provider>, |
| 42 | + document.getElementById('root') |
| 43 | + ) |
| 44 | +``` |
| 45 | + |
| 46 | + |
| 47 | +**Usage with React Router** |
| 48 | + |
| 49 | +```js |
| 50 | + import React from 'react'; |
| 51 | + import ReactDOM from 'react-dom'; |
| 52 | + import { Provider } from 'react-redux'; |
| 53 | + import { Router, Route } from 'react-router-dom'; |
| 54 | + |
| 55 | + import { App } from './App'; |
| 56 | + import { Foo } from './Foo'; |
| 57 | + import { Bar } from './Bar'; |
| 58 | + import createStore from './createReduxStore'; |
| 59 | + |
| 60 | + const store = createStore(); |
| 61 | + |
| 62 | + ReactDOM.render( |
| 63 | + <Provider store={store}> |
| 64 | + <Router history={history}> |
| 65 | + <Route path="/" component={App}> |
| 66 | + <Route path="foo" component={Foo}/> |
| 67 | + <Route path="bar" component={Bar}/> |
| 68 | + </Route> |
| 69 | + </Router> |
| 70 | + </Provider>, |
| 71 | + document.getElementById('root') |
| 72 | + ) |
| 73 | +``` |
| 74 | + |
| 75 | + |
0 commit comments