I have a controlled input where its value and onChange event are set via props. When the selectedValue
prop changes, onInputChanged
callback gets triggered, but if I try accessing selectedValue
in this callback it's out of date.
Seems like when selectedValue
changes, onInputChanged
gets called before it has been updated with the new dependencies
I'm probably just not understanding the lifecycle of the component correctly, but is there a way to ensure that I can access the latest selectedValue
from inside the onChange event? Here's my code:
const TestInput = ({ onChange, selectedValue }) => {
const onInputChanged = React.useCallback(content => {
// Will not log the latest selectedValue
console.log(selectedValue);
onChange(content.target.value);
}, [selectedValue]);
return (
<input value={selectedValue} onChange={onInputChanged} placeholder="Test...." />
);
};
const TestContainer = () => {
const [value, setValue] = React.useState('');
return <TestInput selectedValue={value} onChange={setValue} />;
};
Heres a sandbox link to play around with - https://playcode.io/1042642