0

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

1 Answers1

0

It is not possible to access it from the onChange function, since the function will not be rendered twice to show the new value, you could check it in a useEffect here documentation link.

You could try something like this:

const TestInput = ({ onChange, selectedValue }) => {
  useEffect(() => {
   console.log('selected value', selectedValue);
  }, [selectedValue]);

  const onInputChanged = React.useCallback(content => {
    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} />;
};