React-Redux

Cho Zin Thet
2 min readDec 13, 2020

In redux in react story, I explained

  • create store
  • reducer function
  • action creator

Now we will connect redux with react using react-redux module.

connecting redux with react

In redux in react story, we created a new app installing redux. So we don’t need to install redux and we will install only react-redux.

***to use redux in react we need both packages (redux, react-redux)

Install react-redux

$ npm install react-redux

in src/index.js

  • add bolded part
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
function reducer(state = 0, action){
switch(action.type){
case "Add": state = state + 1; break;
case "Sub": state = state -1; break;
default : return state;
}
return state;
}
const store = createStore(reducer);ReactDOM.render(
<React.StrictMode>
<Provider store = {store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

above codes are the same with Using redux in react that I explained. But in this case we use Provider to connect with react.

in src/App.js

we will now create two buttons of add and subtract of store data and header tag to show the result. In addition some code to connect react with redux, I will explained you later.

import React from 'react';
import {connect} from 'react-redux';
const App = (props)=> {
function add(){
props.add();
}
function sub(){
props.sub();
}
return <div>
<h1>{props.data}</h1>
<button onClick={add}>+</button>
<button onClick={sub}>-</button>
</div>
}
function mapStateToProps(data){
return {
data: data
};
}
function mapDispatchToProps(dispatch){
return {
add(){
dispatch({type: 'Add'})
},
sub(){
dispatch({type: 'Sub'})
}
}
}
const connectToStore = connect(mapStateToProps, mapDispatchToProps)(App);export default connectToStore;

Firstly, see mapStateToProps and mapDispatchToProps are connect with App.

mapStateToProps return an object and store data inside (from store data in index.js) and we use that data in h1 tag of App component that h1 will show changed data in store. (props.data).

mapDispatchToProps return an object and functions inside that pass to store with dispatch method.

*********

onClick=>add()=>props.add()=>dispatch(actiontype)=>state=state+1;

  • ********
react-redux

--

--