Skip to content

Instantly share code, notes, and snippets.

@csorlandi
Created May 18, 2022 01:19
Show Gist options
  • Save csorlandi/1bd1f33315fb76c6eb62e1b1e49cb6e4 to your computer and use it in GitHub Desktop.
Save csorlandi/1bd1f33315fb76c6eb62e1b1e49cb6e4 to your computer and use it in GitHub Desktop.
import { useReducer } from 'react';
const initialState = {
counter: 0,
};
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENTAR':
return {
counter: state.counter + action.payload,
};
case 'DECREMENTAR':
return {
counter: state.counter - 1,
};
case 'REINICIAR':
return {
counter: action.payload,
}
default:
return state;
}
};
export default function Contador() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<h1>A contagem é {state.counter}</h1>
<div>
<button onClick={() => dispatch({
type: 'DECREMENTAR'
})}>Decrementar</button>
<button onClick={() => dispatch({
type: 'INCREMENTAR',
payload: 1,
})}>Incrementar +1</button>
<button onClick={() => dispatch({
type: 'INCREMENTAR',
payload: 2,
})}>Incrementar +2</button>
<button onClick={() => dispatch({
type: 'REINICIAR',
payload: 0,
})}>Reiniciar</button>
</div>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment