Skip to content

Instantly share code, notes, and snippets.

@rikwatson
Created August 30, 2018 14:40
Show Gist options
  • Save rikwatson/7c91ff983bae5c2373b4c5271a687f1e to your computer and use it in GitHub Desktop.
Save rikwatson/7c91ff983bae5c2373b4c5271a687f1e to your computer and use it in GitHub Desktop.
Using a separate object to handle state in React
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const actions = {
init() {
return { value: 0 };
},
increment(state) {
return { value: state.value + 1 };
},
decrement(state) {
return { value: state.value - 1 };
}
};
class App extends React.Component {
state = actions.init();
handleIncrement = () => {
this.setState(actions.increment);
};
handleDecrement = () => {
this.setState(actions.decrement);
};
render() {
return (
<div>
<h2>{this.state.value}</h2>
<button onClick={this.handleIncrement}>+</button>
<button onClick={this.handleDecrement}>-</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
@rikwatson
Copy link
Author

From here

Note that all state information is maintained in actions.

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