Skip to content

Instantly share code, notes, and snippets.

@gaearon
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
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
Copy link

evgenyrodionov commented Feb 3, 2018

@kushalmahajan
Copy link

kushalmahajan commented Nov 7, 2018

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

@kenotron
Copy link

kenotron commented Mar 2, 2019

It's 2019. useReducer :)

@JamesBissick
Copy link

JamesBissick commented May 28, 2021

It's 2019. useReducer :)

This is from 5 years ago.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment