Formik setValues() throws 'Too many re-renders' error #3113
Replies: 1 comment
-
It's pretty hard to get that error in React without actually having an infinite loop. The depth that is required to get to TOO_MANY_RENDERS is pretty deep. Therefore, it's fair to assume there is a bug leading to an infinite loop in your code. It would be really easy to prove this in a codesandbox. However, if we combine all the code running on each render, we should be able to see what's going wrong: // this is basically what happens on every render
// valid "ms" options
const msOptions = ['one', 'two', '']
// selected "ms" option
const ms = values?.status?.toLowerCase()
// this is extremely hard to understand, double negatives all over the place
// I think it should be like `if (msOptions.contains(ms))` but I have read it 15 times and still am not sure I understand the intent
if (!msOptions.every((option) => ms !== option)) {
setValues({
...values,
first_name: '',
last_name: '',
middle_name: '',
})
} Because setValues does not change I'd recommend breaking out some of the complex functionality into a function with a name which describes what you're trying to achieve, like, |
Beta Was this translation helpful? Give feedback.
-
I am trying to use
setValues
to clear ONLY SOME KEYS in Formik state via the functionclearCurrentEntries
, but no matter what I do, I get the error `Too many re-renders. React limits the number of renders to prevent an infinite loop.Beta Was this translation helpful? Give feedback.
All reactions