Skip to content

Instantly share code, notes, and snippets.

@conorhastings
Last active March 30, 2017 20:36
Show Gist options
  • Save conorhastings/b00a2347cb97a65c5cd99f30c6b69bf7 to your computer and use it in GitHub Desktop.
Save conorhastings/b00a2347cb97a65c5cd99f30c6b69bf7 to your computer and use it in GitHub Desktop.
you can enact most of the behavior of redux with a simple component
/* this lacks subscribe behavior or ability to dispatch from outside of component tree but that is generally not neccesary */
class State extends React.Component {
constructor(props) {
super(props);
this.state = YOUR_INITIAL_STATE;
}
reducer = (action, state, props) => {...newState};
/* setState takes an object of new state as first arg or a function of props and state that returns new state
* which we will use here
* we pass dispatch around and use it similarly to redux dispatch
*/
dispatch = action => this.setState(reducer.bind(null, action));
render() {
return <App {...this.state} {...this.props} dispatch={this.dispatch} />;
}
}
/* we can also use a HOC to maintain state for a specific subtree */
function stateHOC(Component, initState, reducer) {
return class State extends React.Component {
constructor(props) {
super(props);
this.state = initState;
}
dispatch = action => this.setState(reducer.bind(this, action));
render() {
return <Component {...this.state} {...this.props} dispatch={this.dispatch} />;
}
}
}
@conorhastings
Copy link
Author

@tiansijie it's just pseudocode representing the fact that function will return a new state object

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