Add Redux to CRA or create react app

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.

yarn global add create-react-app
create-react-app reduxdemo
cd reduxdemo
yarn start

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.

import { combineReducers } from 'redux';

const rootReducer = combineReducers({
    dummy: x => x || {}
});

export default rootReducer;

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.

import rootReducer from './rootReducer';
import { createStore } from 'redux';

const store = createStore(rootReducer, {});

export default store;

Provider

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

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './admin/App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import store from './store/store';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root'));
registerServiceWorker();

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.

 

Related Posts

Leave a Reply

Your email address will not be published.