Created
April 30, 2020 07:58
-
-
Save fwon/c75a7500fc252406dacd9bc002e26ed0 to your computer and use it in GitHub Desktop.
hooks reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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