Skip to content

Instantly share code, notes, and snippets.

@fwon
Created April 30, 2020 07:58
Show Gist options
  • Save fwon/c75a7500fc252406dacd9bc002e26ed0 to your computer and use it in GitHub Desktop.
Save fwon/c75a7500fc252406dacd9bc002e26ed0 to your computer and use it in GitHub Desktop.
hooks reducer
// reducer
function todosReducer(state, action) {
switch (action.type) {
case 'add':
return [...state, {
text: action.text,
completed: false
}];
// ... other actions ...
default:
return state;
}
}
// hooks
function useReducer(reducer, initialState) {
const [state, setState] = useState(initialState);
function dispatch(action) {
const nextState = reducer(state, action);
setState(nextState);
}
return [state, dispatch];
}
// component
function Todos() {
const [todos, dispatch] = useReducer(todosReducer, []);
function handleAddClick(text) {
dispatch({ type: 'add', text });
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment