Implementing Redux in React

Uriel Rodriguez
The Startup
Published in
5 min readOct 25, 2020

To quickly recap ideas from my last blog, Understanding Redux, Redux is a state management library. It establishes the idea of a centralized global state and prevents components from directly accessing and altering the information stored in the global state. By doing so, it establishes a uniform flow of information, unlike React where information flows up and down a component tree. Components are provided with the ability to trigger an update event by dispatching an action that informs a receiver function known as a reducer of the specific way the state should be updated. The reducer uses the information stored in the action, updates the state and the component is then, and automatically, provided with the updated information via its subscription to the global state. After understanding this basic flow, you can begin implementing Redux. To start off, you will have a few libraries:

npm i --save redux react-redux

Here we are first installing the Redux library and the second library “react-redux” connects Redux and the global state to the React application. After this is done, we can begin configuring the React application.

// index.jsimport React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './App';
import reducer from './store/reducer';
const store = createStore(reducer);const app = (
<Provider store={store}>
<App />
</Provider>
);
ReactDOM.render(app, document.getElementById('root'));

Let’s breakdown the first step. Redux is configured within the same file that React is set up, in the index.js file. First, the “createStore” function is imported which, as the name implies, helps to create the central store or the global state for Redux. Next, the “Provider” helper component is imported which helps to connect the React application to Redux, giving it access to the global state. Afterward, an import of a placeholder “reducer” is made for the sake of setting up the initial configuration within the index.js file. The import accesses a reducer file from a directory named “store.” This is the convention to create a directory named store that will contain all Redux code. Next, the global state is created using the createStore function, and it takes in as an argument the reducer, not yet created, that was imported, which will connect the reducer to the created global state. Finally, the Provider helper component wraps the App component allowing the React application a connection to Redux and its global state. Also, note that the Provider component takes in a mandatory prop called store and is passed the store that was created with the createStore function, and the reducer passed as an argument. With this, the React application is now connected to Redux.

After configuring Redux, we move to actually creating the reducer.js file within a directory named “store” which will contain all Redux-related code.

// within src/store/reducer.jsconst initialState = {
someProp: someValue,
anotherProp: anotherValue
};
const reducer = (state=initialState, action) => {
switch(action.type) {
case 'SOME_ACTION':
return {
...state,
someProp: someValueUpdated
};
case 'ANOTHER_ACTION':
return {
...state,
anotherProp: anotherValue + action.actionPayload
};
default:
return state;
}
};
export default reducer;

Alright to start off, a reducer acts on the global state, updating it based on the information it receives from an action. And in order for a reducer to begin updating the global state, it needs to be defined. To do this, an initial state can be created with some starting properties. Next, the reducer function is defined, and it takes two arguments, the initial state and the action that will inform it on how to update the global state. By convention, the reducer is written with a switch statement and will return a new state with some update based on the type of change stored in the action. Also to note, the action types or the type property on the action object stores an all upper case string, again this is the convention. In the case of ‘ANOTHER_ACTION’, the state is updated using a payload which is simply another property, besides the type property, on the action object. That property holds some value that is used in some way to update the global state. With this, the reducer is set up and exported and has been configured within the index.js file. Now all that is left is to connect, or subscribe, the React component to the Redux state.

In order to connect the React component to the Redux state, it has to be configured.

import React, { Component } from 'react';
import { connect } from 'react-redux';
class SomeComponent extends Component {
// code
}
mapStateToProps = state => {
return {
someProp: state.someProp,
anotherProp: state.anotherProp
};
};
mapDispatchToProps = dispatch => {
return {
updateSomeProp: () => dispatch({ type: 'SOME_ACTION' }),
updateAnotherProp: () => dispatch({
type: 'ANOTHER_ACTION',
payload: someValue
})
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent);

The very first thing that is needed to subscribe the component to the Redux state is to import the “connect” function. This function takes in two functions as arguments, “mapStateToProps” and “mapDispatchToProps.” It then returns a higher-order component that takes in the React component as an argument, connecting it to Redux. The two map functions serve to provide the component access to properties in the global state and a means to dispatch actions that trigger state updates. The first function mapStateToProps does as its name implies and maps the properties in the global state to props that will be passed down to the React component via the higher-order component that is returned from the connect function. The function takes in the global state as an argument and returns a map, an object with properties identical to the ones in the global state and is assigned the values by reaching into the state object and accessing the same property. The second function, mapDispatchToProps, receives the “dispatch” function, which is provided by Redux, as an argument that is used to send an action to the reducer to update the global state. It then returns an object mapping different functions that receive the dispatch function as a callback providing it the action object. The first dispatch function simply contains an action with the mandatory “type” property, while the second dispatch function contains an action with a payload. And again, the payload property can be named anything, it is only a property with some value needed to update the global state. With these setups, React is now using Redux to manage state. For additional organization, the actions passed into the dispatch functions can be stored within their own file, action.js, and then imported into the component file.

Albeit a little work in the initial setup, implementing Redux can reduce the complexity of a React application, especially as it grows. It ensures that any component can access the global state by subscribing the component to it. It can also handle asynchronous operations modifying how actions are created and provided to the dispatch functions. You can check out my first blog on Redux to become familiar with the Redux workflow and learn more on Redux from their docs.

https://redux.js.org/

--

--

Uriel Rodriguez
The Startup

Flatiron School alumni and Full Stack web developer.