This is my summary of the bare minimum steps as a quick-ref cheatsheet for adding Redux to an existing React app. This is just some notes for future reference. If you’re looking for tutorials, take a look at:
- https://redux.js.org/introduction/getting-started
- https://react-redux.js.org/introduction/quick-start
Here’s my quickref:
npm install --save react-redux
Add Redux devtools for Chrome (see here):
npm install --save-dev redux-devtools-extension
Wrap <Provider> around root Component to share the Store with all child components:
import { Provider } from 'react-redux' import store from './store' <Provider store={store}> <App> </Provider>
Implement mapStateToProps and mapDispatchToProps to pass store and dispatch() as props to each Component, and call connect() to connect each Component with your Redux Store:
const mapStateToProps = (state) => { return { yourcomponent: state.yourcomponent } } export default connect( mapStateToProps, mapDispatchToProps )(YourComponent)
Create a Store:
import { createStore } from 'redux'; import { devToolsEnhancer } from 'redux-devtools-extension'; let store = createStore(yourReducer, devToolsEnhancer()); export default store;
Create reducers for Store – here’s an example that take the the value of a label from the passed action payload and sets it in the Store – remember the state of the store is always treated as immutable, so always create a new copy of the modified state, here using Object.assign():
function labelReducer(state = initialState, action) { switch (action.type) { case 'CHANGE_LABEL': return Object.assign( {},{ labelValue : action.payload } ); default: return state; } }
Implement an action creator that builds an Action object that requests changes to the Store – each action has a type and a payload:
export function changeLabel(payload) { return { type: "LABLE_CHANGE", payload } };
Implement mapDispatchToProps – you can either build the Action object yourself here, or call an Action creator like the above example:
function mapDispatchToProps(dispatch) { return { changeLabel: labelValue => dispatch(changeLabel(labelValue)) }; }
Pass mapDispatchToProps to your connect() call shown earlier.
As a comparison, here’s a simple React app using Flux:
https://github.com/kevinhooke/SimpleReactFluxExample
… and here’s the same app converted to use Redux:
https://github.com/kevinhooke/SimpleReactReduxExample
Done!