When 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;
Top comments (5)
I think you need to pass value as dependency to useCallback instead of setValue ?
The value used inside handleChange is event.target.value different from outside value.
I mean instead of
const handleChange = useCallback(
event => {
setValue(event.target.value);
},
[setValue]
);
this you can write
const handleChange = useCallback(
event => {
setValue(event.target.value);
},
[value]
);
Hmm. I don't think value needs to be passed as dependency since it not being used but I need to check.
I think your original code is correct and adding
value
as a dependency would be a mistake. It's not referenced inside the callback, nor should it be added as a dependency, otherwise your callback function would be re-created on every single value change, which would defy the purpose of using that callback hook there. There's no reason for your event handler to change when the input value changes.React's console output usually contains good information and warning messages about missing dependencies. So if
value
or anything else was required for your callback you would see that in your log output.