Skip to content

Instantly share code, notes, and snippets.

@gaearon
Created September 19, 2016 19:23
Show Gist options
  • Save gaearon/64e2c4adce2b4918c96c3db2b44d8f68 to your computer and use it in GitHub Desktop.
Save gaearon/64e2c4adce2b4918c96c3db2b44d8f68 to your computer and use it in GitHub Desktop.
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

From line 17:

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

should probably be more like:

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

@imevro
Copy link

imevro commented Feb 3, 2018

@kvedantmahajan
Copy link

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

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