Skip to content

Instantly share code, notes, and snippets.

@velopert
Last active April 1, 2023 13:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velopert/e0d5a027f60a7368b2bb6f9277e3f742 to your computer and use it in GitHub Desktop.
Save velopert/e0d5a027f60a7368b2bb6f9277e3f742 to your computer and use it in GitHub Desktop.
import { useReducer, useCallback } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'CHANGE':
return {
...state,
[action.name]: action.value
};
case 'RESET':
return Object.keys(state).reduce((acc, current) => {
acc[current] = '';
return acc;
}, {});
default:
return state;
}
}
function useInputs(initialForm) {
const [form, dispatch] = useReducer(reducer, initialForm);
// change
const onChange = useCallback(e => {
const { name, value } = e.target;
dispatch({ type: 'CHANGE', name, value });
}, []);
const reset = useCallback(() => dispatch({ type: 'RESET' }), []);
return [form, onChange, reset];
}
export default useInputs;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment