I have a complex form which contains input elements of different types. For simplicity I will limit this to one, since each effectively follows the same approach.
const Form = () => {
const [state, setState] = useState();
const handleChange = useCallback((name, value) => {
setState({
...state,
[name]: value
})
}, [state, setState]);
useEffect(() => {
console.log(state)
}, [state, setState]);
return (
<div>
<Input name="inputOne" onChange={handleChange} />
<Input name="inputTwo" onChange={handleChange} />
</div>
);
}
const Input = ({ name, onChange }) => {
const [value, setValue] = useState("");
const handleChange = useCallback((e) => {
setValue(e.target.value);
onChange(name, e.target.value)
}, [value, setValue]);
return (
<input onChange={handleChange} value={value}/>
);
}
For some reason when using this form. If I enter values into the first input I get the result logged as
{ "inputOne": "value entered into input one" }
but then if I enter something into the second input I get this
{ "inputTwo": "value entered into input two" }
If I then go back and type into inputOne again we get this again.
{ "inputOne": "value entered into input one, and more text entered" }
To my knowledge, the code I have written should update the callback when the state changes so the new state that is spread (...state) is the latest state value. This is then updated in all the elements that I pass the handleChange function into. However it appears that handleChange is not updated where it is passed into the onChange parameter so the old callback is called with the state property being saved incorrectly.
Can someone tell me if this is correct and that the handleChange callback isn't being updated correctly? It's like both Input are seeing different references to the handleChange callback.