setState called in render prop is causing a react warning

In order to avoid this issue with Formik, you can wrap your state calls in setTimeouts, this should do the deal:

        setTimeout(() => setHasValidationError(true), 0);

This is also what Formik does in their official documentation. It's a problem they have had for a while, the trick is to make the state update run on the next cycle tick.

Also see: https://github.com/jaredpalmer/formik/issues/1218


I think Ali's answer using setTimeout is legit. I'd like to add that useEffect is IMO better solution. For it further prevent the unlikely but still possible error case when setHasValidationError is called after the component got unmounted.

(eslint naively complains useEffect is unsafe to use here but I checked with source code it's totally fine.)

// here I rename useEffect to mute eslint error
const nextTick = useEffect;

<Formik>
  {({
    isSubmitting,
    submitCount,
    isValid,
    errors,
    values
  }: FormikProps<V>) => {
    const invalid = !isValid;

    nextTick(() => {
      if (submitCount > 0 && invalid) {
        setHasValidationError(true);
      }
    }, [submitCount, invalid]);

    // ...
  }
</Formik>

Tags:

Reactjs