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.

Next step is to implement counter through Redux store

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

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

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.

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.

A working example of counter app can be found here

See also: This react app example

Leave a Reply