Skip to content

Instantly share code, notes, and snippets.

@omar2205
Created June 23, 2020 12:04
Show Gist options
  • Save omar2205/0f585a18df3da15f773e1a43dbe02a04 to your computer and use it in GitHub Desktop.
Save omar2205/0f585a18df3da15f773e1a43dbe02a04 to your computer and use it in GitHub Desktop.
react useReducer quick
const initialState = {
counter: 0
}
const counterReducer= (state, event) => {
if (event.type === 'INC') {
return {
...state,
counter: state.counter +1
}
}
if (event.type === 'DEC') {
return {
...state,
counter: state.counter -1
}
}
}
const App = () => {
const [state, dispatch] = React.useReducer(counterReducer, initialState)
return (
<div>
<h1>{state.counter}</h1>
<p onClick={() => dispatch({type: 'INC'})}> + </p>
<p onClick={() => dispatch({type: 'DEC'})}> - </p>
</div>
)
}
const el = document.getElementById('app')
ReactDOM.render(<App />, el)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment