Changing value and suffix at the same time causes Maximum update depth exceeded error
See original GitHub issueI’m using react-number-format in combination with Formik and material-ui. I have a use case when I need to call Formiks resetForm and it updates value and a suffix at the same time. E.g. (100 m to 0 ft ).
const NumberFormatCustom = (props: *): NumberFormat => { const { inputRef, onChange, unit, ...other } = props; return ( <NumberFormat {...other} getInputRef={inputRef} onValueChange={values => { onChange({ target: { value: values.value, name: other.name, }, }); }} suffix={unit} /> ); };
NumberFormat is passed though InputProps to TextField.
InputProps={{ inputComponent: NumberFormatCustom }}
This is the console log that shows Maximum update depth exceeded error.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:19 (5 by maintainers)
Top GitHub Comments
I think the problem comes from L134 in
<NumberFormat>
: https://github.com/s-yadav/react-number-format/blob/81ef1cfe38cd06b50e1e9753ff956abefead4da4/src/number_format.js#L134When a component is re-rendered, the
props
andprevProps
will not be the same instance, so this expression will always betrue
?I’ve noticed a situation when a user types really fast, there is a chance that this component gets re-rendered (for any reason):
setState()
insideupdateValue()
(triggered fromonChange
), butsetState()
callback is called (so a ancestor component gets notified of new value)And thus the component is rendered with old value when it’s controlled, and it always override its state even when the value in state is actually newer.
After that the callback is finally fired, bringing value to its ancestor component, and triggered another re-render. In my case this is where the whole thing goes into an infinite loop.
I think I found a workaround by using
This briefly switches the component to uncontrolled if there’s now valid input and breaks the infinite loop.