Redux In React

Cho Zin Thet
2 min readDec 13, 2020

Firstly I’m gonna show two parts. The first part is store data using redux npm package and second part is store data and show that data in react component using react-redux npm package.

Using redux in react

Using redux, our data will collect in one place. That is redux store. We can store in there and change data with passing action.

Now we will create a simple react app using redux.

Create new react app

  • create new react app with create-react-app
  • change directory to your project folder

Install redux npm

  • npm install redux (Install redux to your project)
$ npm install redux

Import 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';
function reducer(state = 0, action){
if(action.type === 'ADD'){
state++;
console.log(state);
return state;
}else{
console.log(state);
return state;
}
}
const store = createStore(reducer);store.dispatch({type: 'ADD'});ReactDOM.render(
<React.StrictMode>
<App />
</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();

run with the command

$ npm start

In the console you will see the result 1.

and remove a line store.dispatch and run again.

store.dispatch({type: 'ADD'});

You will see the result 0 in the console.

Why is that?

firstly we create store “const store = createStore(reducer);” and reducer function. Reducer function have initial data of 0 (that is store data) and that accept actions and change initial data as match action type.

In our reducer function, when action are passed with the type of ‘ADD’ , state increase (especially store data change) 1 and become state = 1 from state = 0

And finally dispatch function pass an action to store reducer with action type ‘ADD’. So our state change 0 to 1. If we don’t pass any dispatch method to store, our store will never change (state = 0).

connecting redux with react

Now when we want to change data in store, we will pass dispatch method. We don’t want to do that. When we click on html button or something , the store data change and show the result back to us.

And then we need to know about react-redux package to connect both.

In the story of react-redux I explained connecting redux with react

react-redux

--

--