'React native Text Input selection and onSelectionChange creates flickering when we reformat text in onChangeText

I reformat a string to Mobile number format '(123) 456-7890' while user enter number input.

When the Text input has value like '(123) 4' and the user moves the cursor after 3. '(123|) 4' (| => consider this as cursor) and deletes the 3 by click backspace, i reformat the string by also deleting the ') '. so it will look like this '(124'.

This formatting part works fine. only problem is the cursor moves to position '(1|24' (next to 1). expected cursor position is '(12|4'

To handle the cursor position i added the selection and onSelectionChange props to my TextInput.

<TextInput
          keyboardType="number-pad"
          selection= {mySelection}
          onSelectionChange={handleMySelection}
          value={number}
          onChangeText={(text) => {formatNumber(text); }}
        />
const [mySelection, updateMySelection] = useState({start : 0, end: 0});
  const handleMySelection = ({ nativeEvent: { selection, text } }) =>{
    updateMySelection(selection);
  }

by just adding the above selection and onSelectionChange, the cursor flickers when i enter the number faster. Especially where i add bracket, space and hyphen while formatting text. By flickers, i mean cursor position changing to previous position, not updating instantly.

Even though, i didn't add any additional functionality to handleMySelection(), this flickering occurs. when i comment the selection and onSelectionChange, cursor flickering doesn't occur and the input works smoothly.

Please suggest a solution to position the cursor at desired position without cursor flicker.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source