Simple React hook to handle input
reactjavascriptreacthooksWhen building in react often you have to deal with different inputs like text, number, date... and each time it is kind of annoying to write onChange handlers with same boiler plate code to handle the local state. I wrote a really simple hook to avoid that boiler plate
import { useState, useCallback } from 'react';
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue);
const handleChange = useCallback(
(event) => {
setValue(event.target.value);
},
[setValue],
);
return { value, handleChange, setValue };
};
export default useInput;
and you can use this as follows
import useInput from './useInput';
const App = () => {
const { value, handleChange } = useInput('');
return <input value={value} onChange={handleChange} />;
};
export default App;