Found my team doing this and it feels like code smell, but I can't explain why. Formik documentation doesn't specifically address this, because why would it?
I'm working on a project with some team members that involves a complicated nested form. Imagine this grossly oversimplified example:
//main component
<Formik
onSubmit={async (values) => {
const payload = {'firstName': firstName, 'lastName': lastName}
console.log(payload); //or do whatever with the payload
}}
>
<Form>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="Jane" />
<label htmlFor="lastName">Last Name</label>
<Field id="lastName" name="lastName" placeholder="Doe" />
<SubComponent/>
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);
//SubComponent:
const {values, setFieldValue} = useFormikContext();
const handleClick = ()=> {
if (values.firstName){
setFieldValue("showAdvancedOptions", true)
}}
return (<button onClick= {handleClick}>
values.showAdvancedOptions && //render some more stuff)}
In other words, we're putting things that I assumed should be managed with pure React state into Formik, and using it as a state or context manager. On submit, the submit function pulls out the values of the form that are actually needed as part of the payload and constructs the payload from those, throwing away the values that were only used to track state. This strikes me as bad, but maybe it's actually good. After all, Formik's useFormikContext can be accessed at any level of the form, and ours does, sadly, have quite a few nested components.
Is there any reason not to use this pattern?