Skip to content

Instantly share code, notes, and snippets.

@ohansemmanuel
Last active April 13, 2019 11:33
Show Gist options
  • Save ohansemmanuel/69f2269f17bcfb26ab0bbdc0717f4215 to your computer and use it in GitHub Desktop.
Save ohansemmanuel/69f2269f17bcfb26ab0bbdc0717f4215 to your computer and use it in GitHub Desktop.
const initializeState = () => ({
width: 100
})
// ✅ note how the value returned from the fn above overrides initialState below:
const initialState = { width: 15 }
const reducer = (state, action) => {
switch (action) {
case 'plus':
return { width: state.width + 15 }
case 'minus':
return { width: Math.max(state.width - 15, 2) }
default:
throw new Error("what's going on?" )
}
}
const Bar = () => {
const [state, dispatch] = useReducer(reducer, initialState, initializeState)
return <>
<div style={{ background: 'teal', height: '30px', width: state.width }}></div>
<div style={{marginTop: '3rem'}}>
<button onClick={() => dispatch('plus')}>Increase bar size</button>
<button onClick={() => dispatch('minus')}>Decrease bar size</button>
</div>
</>
}
ReactDOM.render(Bar)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment