jackocnr / intl-tel-input

A JavaScript plugin for entering and validating international telephone numbers. React and Vue components also included.
https://intl-tel-input.com
MIT License
7.69k stars 1.95k forks source link

React: Endless loop when using dynamically assigned methods in React component #1853

Open JensDebergh opened 3 weeks ago

JensDebergh commented 3 weeks ago

Plugin version

e.g. v24.6.0 (please try latest version)

Steps to reproduce

Initialize

<IntlTelInput
        onChangeNumber={(telephoneNumber) => this.onChangeNumber(index, telephoneNumber)}
        initialValue={initialValue}
        initOptions={{
          initialCountry: initialCountry,
          formatOnDisplay: true,
          formatAsYouType: true,
        }}
      />

When providing a dynamically assigned variable (for example when using this inside of a .map of items), it keeps triggering onChangeNumber in an endless loop and freezing the browser.

Expected behaviour

Should not trigger endlessly.

Actual behaviour

Triggers endlessly and freezing the browser as a result.

Initialisation options

I'm using utilsScript

jackocnr commented 2 weeks ago

Thanks for reporting this. I don't have time to look into this myself right now, but the react component is actually quite simple if you want to look into this yourself.

For reference, it might be useful to share a link to a codepen reproducing the issue - here's one with the react component up and running - you could fork this if it helps.

roivasxxx commented 2 weeks ago

Also had an issue, where my App would get into an infinite loop. In my case the IntlTelInput component is being used in a form (first its wrapped in a custom component). The form uses a state, that is an object. On each rerender the IntlTelInput would fire the onChangeNumber function, which would set my state and that would cause a rerender, which would cause the onChangeNumber function to fire,.. etc. etc. Obviously just using a state with a simple string, number, etc. doesnt cause this infinite rerendering.

To resolve the issue I just wrapped my custom component in a memo and called it a day.

jackocnr commented 2 weeks ago

Thanks. This is a good point: if the react component is firing onChangeNumber on each render, then that is a bug which we should fix. Again, I don't have time myself right now to look into this, but I would welcome a pull request.