Overview

Redux is most commonly used in React in order to manage state. As an application grows larger the number of states each part must manage increases as well. If multiple models and models can update the same model you will lose track of what is going one eventually. In order to simplify this Redux tries to make state mutation more predictable.

Installation

To install Redux you just need to run the command

npm install redux
npx create-react-app my-app — template redux

Actions

There are 3 main parts to Redux: action. state and store. Actions contains the data that you want to send to the store. To send them to the store you need to use

store.dispath()
export const ADD_TODO = 'ADD_TODO'
export function addTodo(text) {
return { type: ADD_TODO, text }
}

Reducer

The reducer is what tells the application how to handle the data. For example, when adding and removing data you might be sending the same type of data. In order to differentiate the two actions the reducer uses the action to decide whether it will add or remove the data. An example of a reducer would be

function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [
...state,
{
text: action.text,
completed: false
}
]
case REMOVE_TODO:
return [
...state.filter(todo => todo.text !== action.text)
]
default:
return state
}
}
}

Store

The store is what brings together the action and reducer. It holds the data allows the data to be updated. The code for the store is simple

import { createStore } from 'redux'
import todoApp from './reducers'
const store = createStore(todoApp)

Thunk

React by default is handled synchronously and that might bring its own set of problems. To change it to asynchronous one option is to use redux-thunk. To install it use the command

npm install redux-thunk
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';

import rootReducer from './reducers';
import App from './App';

// use applyMiddleware to add the thunk middleware to the store
const store = createStore(rootReducer, applyMiddleware(thunk));

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

Conclusion

While Redux can make managing data easier in a big application the use of Redux in a small application is not necessary. React also has its own way of managing data called context so that might also be an alternative. Redux is unidirectional so all data follows the same lifecycle pattern. Having a single source of truth for the data ensures that there is no conflicting information in you application.

Written by

Hi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store