This repo was meant to be as simple redux as possible for learning purpose only. There are two branch on this repo, First is the master and the refactored branch. I supposed that we understand the theoretical concept already.
In the nutshell, what I understand redux has to have
- Global store,
- Actions which is plain javascript object then dispatch them and
- Reducer to update the state.
Be sure to install react-redux, redux library first bynpm i react-redux redux --save
There are two repos here, master and refactoring
- Create store where reducer is passed as argument
const store = createStore(counterReducer);
- Define the actions as object, and passed as an argument in the dispatch function
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
- Tell reducer to take the action of updating
const initState = {
count: 0
}
const counterReducer = (state = initState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1
}
case 'DECREMENT':
return {
count: state.count - 1
}
default:
return state
}
}
The result can be console logged as in the picture shown
- Now, let's use App component, and pass the data as props. But before that, we need to make data available in the
App.js
component by using Higher Order component function which is connect. Let's define a function for that purpose
const mapStateToProps = (state) => {
return {
counter: state.count
}
}
- Also we want to have function available in our
App.js
, so we map it as props
const mapDispatchToProps = (dispatch) => {
return {
increment: () => {
dispatch(INCREMENT);
},
decrement: () => {
dispatch(DECREMENT);
}
}
}
And here is what the App.js
looks like
const App = (props) => {
return (
<div className="App">
<h1>Learn React Redux Counter</h1>
<h3>Count: {props.counter}</h3>
<button onClick={props.increment}>+</button>
<button onClick={props.decrement}>-</button>
</div>
);
}
- Finally, we wrap our App component with connect function where we pass
mapStateToProps
andmapDispatchToProps
export default connect(mapStateToProps, mapDispatchToProps)(App);
When we npm start
the app, we get visualization as shown. Just pass
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
in the index.js file
const store = createStore(
counterReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
- Practically, we are done. But, to make it more professional, normally for real life application, the app's file structure will be placed separately based on their functionality. So let's refactor it
This step is a no-brainer activities, simply follow the file structure on the refactoring branch
That's all, Mate... Happy Coding