Gilang Chandrasa Thoughts, stories, and ideas

Redux React Counter

You know Redux, right? If you’re into React then you know about Flux concept and you also know that there are already few implementations about Flux architecture.

Redux is not really Flux implementation, but some said it’s better than Flux itself.

So what is Redux?

Redux is a predictable state container for JavaScript apps.

If you want to learn more, you can read Redux documentation or you can watch awesome video on Redux by Dan Abramov (the Redux creator)

Redux React Counter Example

Here what the Redux React Counter tutorial taken from the videos (I change Counter component using React here)

const counter = (state = 0, action) => {
  switch(action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};


class Counter extends React.Component {
  render() {
    return (
      <div>
        <h1>{this.props.value}</h1>
        <button onClick={this.props.onIncrement}>+</button>
        <button onClick={this.props.onDecrement}>-</button>
      </div>
    );
  }
};


const { createStore } = Redux;

const store = createStore(counter);

const render = () => {
  ReactDOM.render(
    <Counter value={store.getState()}
       onIncrement={() => store.dispatch({type: 'INCREMENT'})}
       onDecrement={() => store.dispatch({type: 'DECREMENT'})}
    />, document.getElementById('root')
  );
};

store.subscribe(render);
render();

Click here if you want to see in action.