Field-level validation is incredibly powerful but comes with a pretty notable limitation.
When calling 'validate' provided via useField, there is no way for the provided validation function to have access to the latest Formik state. It's just not currently possible.
In the above example, the validation called on useField will always be 1 render behind.
deliveryDate function is passed to Formik
pickUp value is changed to true
deliveryDate validation fn from step 1 uses old values object in closure (returns valid)
component is re-rendered with new values from useFormikContext
deliveryDate validation call uses new values object in closure (returns invalid)
Suggested Solution
We remove step 4 + 5 from above and instead use a reference object for values returned from useFormikContext (values is updated with new values using mutation). This way we can always access the new values despite validation functions using the useFormikContext from a previous render.
In order to correctly set dependencies for memo hooks, actual values should be set as dependencies - not the top-level values object.
🚀 Feature request
Field-level validation is incredibly powerful but comes with a pretty notable limitation.
When calling 'validate' provided via useField, there is no way for the provided validation function to have access to the latest Formik state. It's just not currently possible.
Example
In the above example, the validation called on useField will always be 1 render behind.
useFormikContext
Suggested Solution
We remove step 4 + 5 from above and instead use a reference object for values returned from useFormikContext (values is updated with new values using mutation). This way we can always access the new values despite validation functions using the useFormikContext from a previous render.
In order to correctly set dependencies for memo hooks, actual values should be set as dependencies - not the top-level values object.
Why would we want this?