Why TextInput's `.clear()` doesn't trigger `onChangeText` callback?

I am programmatically clearing the TextInput’s value via .clear() method.
I also subscribed my state to onChangeText but on .clear() invocation, my state doesn’t change.

Why .clear() doesn’t trigger onChangeText? Isn’t it changing the text value?


function MyComponent() {
  const [value, setValue] = useState("");
  const ref = useRef();

  const handlePress = () => {

  return (
      <TextInput onChangeText={setValue} ref={ref} />;
        onPress={handlePress} // <<< when this is called, onChangeText doesn't called?

>Solution :

In general across multiple different APIs and event systems, when you change the value of a field/control via code, it doesn’t trigger any event handlers related to that change. (There are APIs/systems that are exception to that general rule, but they’re rare.) The event handlers are there for when the change is done via the user operating on the field/control in the UI. For example, with a DOM input element, setting the value property changes the value, but doesn’t trigger any events (such as change or input); submitting a form via its submit function doesn’t trigger a submit event. React Native is just following the same pattern in their fields/controls.

Leave a Reply