Basic Redux Counter example

In this example,

  • The "CounterComponet" is included by the root component called "AppComponent".
  • No Store composition is used here. You still have to pass the props to "AppComponent", which in turn passes them to "CounterComponent"

So it will not demonstrate how good Redux is, but will just let you know the basic ideas of Redux.

class CounterComponent extends Component {

        return (

                <h3>{this.props.counter.value}</h3>    {/* data passed from parent compoent */}
                    <button onClick={ e => this.props.onChange(1)}>+</button>    {/* event handler passed from parent compoent */}
                    <button onClick={ e => this.props.onChange(-1)}>-</button>    {/*  event handler passed from parent compoent */}


class AppComponent extends Component {
  render() {
    return (

      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to {this.props.appName}</h1>

            counter={this.props.counter}   // Relay data from outside React its child component
            onChange={this.props.counterOnChange}    // Relay event handler from outside to its child component


        <ToDoList />


// The bootstrap code using Redux

// the initial state
const initialState = {
    counter: {
        value: 0

// the reducer, which deals with state/action only
function reducer(state=initialState, action){
        case 'counterChange':
            let amount = action.amount ? action.amount: 0;
            return {
                counter: {
                    value: state.counter.value + amount

            return state;


// create a store using the reducer above
const rootStore = createStore(reducer);

//the listener. Normally it can be used to change the display of a component. So we call it "render()"
function render(){
        <AppComponent appName="React Demo Site"
             counter={rootStore.getState().counter}  //pass the data from Redux store to the React root component
             counterOnChange = { (amount) => rootStore.dispatch({type: 'counterChange', amount: amount}) }  //Use event dispatching as event handlers for React components

//// let the listener subscribe the change of state

//Initial page rendering:

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.