Skip to content

Instantly share code, notes, and snippets.

@gaearon gaearon/Counter.js Secret
Created Sep 19, 2016

Embed
What would you like to do?
import React, { Component } from 'react';
const counter = (state = { value: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 };
case 'DECREMENT':
return { value: state.value - 1 };
default:
return state;
}
}
class Counter extends Component {
state = counter(undefined, {});
dispatch(action) {
this.setState(prevState => counter(prevState, action));
}
increment = () => {
this.dispatch({ type: 'INCREMENT' });
};
decrement = () => {
this.dispatch({ type: 'DECREMENT' });
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
@graphicore

This comment has been minimized.

Copy link

graphicore commented Jun 1, 2017

From line 17:

  dispatch(action) {
    this.setState(prevState => counter(prevState, action));
  }

should probably be more like:

  dispatch(action) {
    this.state = counter(this.state, action));
  }
@evgenyrodionov

This comment has been minimized.

Copy link

evgenyrodionov commented Feb 3, 2018

@kushalmahajan

This comment has been minimized.

Copy link

kushalmahajan commented Nov 7, 2018

Probably a good interview question on how to write Redux style code without using Redux

@kenotron

This comment has been minimized.

Copy link

kenotron commented Mar 2, 2019

It's 2019. useReducer :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.