Skip to content

Instantly share code, notes, and snippets.

@dewey92
Last active May 17, 2019 18:57
Show Gist options
  • Save dewey92/6f9b8fe958d0ea5b814c8a65e7ed31d5 to your computer and use it in GitHub Desktop.
Save dewey92/6f9b8fe958d0ea5b814c8a65e7ed31d5 to your computer and use it in GitHub Desktop.
Counter Reducer Solution
// useCounterReducer.js
import * as React from 'react';
// Array destructuring disini sangat membantu code readability
const counterReducer = ([state, effect], action) => {
if (action.type === 'INCREMENT') {
return [state + 1];
}
if (action.type === 'DECREMENT') {
if (state === 0) {
// Raise effect!
return [state, 'INVALID_STATE']
}
return [state - 1];
}
if (action.type === 'RESET_EFFECT') {
return [state];
}
return [state, effect];
}
// Hooks, kita ubah sedikit ya disini biar lebih clean
export const useCounterReducer = () => {
const [stateAndeffect, dispatch] = React.useReducer(counterReducer, [0]);
return [
stateAndEffect,
{
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
resetEffect: () => dispatch({ type: 'RESET_EFFECT' }),
}
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment