How to create simple counter app using Redux with React

Redux is a great tool to manage states. To share state among various components in React is always a challenge. Hence it is very useful and helpful to manage state amongh various components using Redux with React.

(This example here is just the rework from a video tutorial from the author of Redux, Dan Abramov)

Here in the counter app example we will use createStore method of Redux.

Lets start with importing createStore method. In order to use Redux in React you can implement it at the top of app file and import its various methods one of which is createStore.

import { createStore } from 'redux';

Next step is to implement counter through Redux store

const store = createStore(counter);

We haven’t created the reducer function named counter which we implement with createStore yet. To know how reducers work please check this tutorial

const counter = (state=0, action) => {
  
  if(typeof state === 'undefined'){
    return 0;
  }
  
  if(action.type === 'INCREMENT') {
    return state + 1;
  } else if(action.type === 'DECREMENT') {
    return state - 1;
  }else {
    return state;
  }
}

The counter function receives two arguments, state and action. It returns 
either changed state or 0. In case of action type INCREMENT or DECREMENT it changes the state value by performing increment or decrement respectively and returns the changed value. It returns 0 when state is not initialized yet.

Next we create JSX tag to display the counter on the page. Here it is

const Counter = ({value, onIncrement, onDecrement}) => (
  <div>
    <h1>{value}</h1>
    <button onClick={onIncrement}>+</button>
    <button onClick={onDecrement}>-</button>
  </div>
);

This function is quite self explanatory . It displays received value in h1 tag and have two buttons with onIncrement and onDecrement functions fired on respective clicking. We will create these two functions next.

const Increment = () => {
  store.dispatch({
    type:'INCREMENT'
  })
}

const Decrement = () => {
  store.dispatch({
    type:'DECREMENT'
  })
}

Now the last part of code. The actual dom renderer render() , the subscribe() function to initiate the store subscription and finally the rendering of the app on the page.

const render = () => {
  ReactDOM.render(
    <Counter value={store.getState()} onIncrement={Increment} onDecrement={Decrement} />,
    document.getElementById('root')
  )
}
store.subscribe(render);
render();

A working example of counter app can be found here

See also: This react app example

Leave a Reply

Your email address will not be published. Required fields are marked *