Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active October 22, 2018 23:22
Show Gist options
  • Save ryanflorence/51ed3c09be94efb7786a2fe3855ba7c0 to your computer and use it in GitHub Desktop.
Save ryanflorence/51ed3c09be94efb7786a2fe3855ba7c0 to your computer and use it in GitHub Desktop.
Sweatpants
/////////////////////////////////
import React from "react"
import ReactDOM from 'react-dom'
let reducer = (state={count: 0}, action) => {
if (action.type === 'up') {
return {
...state,
count: state.count + 1
}
} else {
return state
}
}
ReactDOM.render((
<StateProvider reducer={reducer}>
<App/>
</StateProvider>
), node)
/////////////////////////////////
let SomeScreen = () => (
<State>
{({ state, dispatch }) => (
<div>
<h1>{state.count}</h1>
<button onClick={() => dispatch({ type: 'up' })}>Up</button>
</div>
)}
</State>
)
import React from "react"
let Context = React.createContext()
class StateProvider extends React.Component {
state = {
state: this.props.reducer(undefined, '@@INIT'),
dispatch: (action) => {
this.setState(state => ({ state: this.props.reducer(state, action)}))
}
}
render() {
let { reducer, ...props } = this.props
return (
<Context.Provider value={this.state} {...props}/>
)
}
}
let State = Context.Consumer
export { StateProvider, State }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment