For many people, adding Redux to a React application may appear as a daunting task. In my opinion, it is not so difficult. With exactly three changes, we can add Redux to an existing react application. For our example, I am going to create the React application using CRA or create-react-app. CRA is a nice utility from Facebook to quickly create React apps. Install CRA globally like so.

We also create a React app called reduxdemo. And start it. The app is available at port 3000 by default.

CRA likes to structure project folders by features. Within a folder, place all the components, stylesheets and tests for a specific feature. If you recollect, Redux has actions. Actions are notifications from the component to update the store. If we use CRA, we should place all the actions within the feature folder. For now, we will worry only about the following three aspects of redux integration.

  1. Root reducer
  2. Store
  3. Provider

Root Reducer

Create a new folder called store. Within the store folder, we place all our reducers, root reducer and the store.

The code for the root reducer is shown below.

Normally, we will import reducers from the same folder and use it within combineReducers. But, we don’t have any reducer yet. So, I have defined a dummy reducer. The dummy reducer accepts a state object and return it. The reducer also initialises the state with an empty object.

Store

The code for creating a store is equally trivial. We use the root reducer to create the store.

Provider

Finally, we use the Provider component from react-redux as the root component. Modify the index.js as shown below.

With these simple changes, we have integrated Redux into our React app. Place all the actions in their respective feature folder. And reducers in the store folder. I hope this blog post reduced some of the fears you had of integrating Redux.

UPDATE:
Screencast which explains the above steps.

 

Add Redux to CRA or create react app
Tagged on: