Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Formik with MobX
function useFormik(props) {
// useState to keep the same observable around without recreating it on each render
const [formik] = React.useState(() =>
values: props.initialValues || {},
touched: {}
// just mutate state, this function itself can be considered an action+reducer
const handleChange = fieldName => event => {
formik.values[fieldName] =;
const handleBlur = fieldName => event => {
formik.touched[fieldName] = true;
// props will be spread over the form inputs minimizing code necessary to setup such input
const getFieldProps = fieldName => ({
value: formik.values[fieldName],
onChange: handleChange(fieldName),
onBlur: handleBlur(fieldName)
return { handleChange, handleBlur, getFieldProps, ...formik };
function NameForm() {
// use the formik hook with optional initial values
const formik = useFormik({
initialValues: {
name: "",
email: ""
const { getFieldProps } = formik;
// notice the useObserver hook that takes care of re-rendering
return useObserver(() => (
<input type="text" {...getFieldProps("name")} />
<input type="text" {...getFieldProps("email")} />
<Debug formik={formik} />
<button type="submit">Submit</button>

This comment has been minimized.

Copy link

@gastonmorixe gastonmorixe commented Jan 8, 2020

This is great, I have started a package using a similar Formik API with MobX because I needed it for a project with derived / calculated props requirements, feel free to check it out


This comment has been minimized.

Copy link
Owner Author

@FredyC FredyC commented Jan 8, 2020

Yea, I already have cooked up some more solid implementation of this used in production.

It's not exactly open-sourced yet. I want to get to it eventually. Polish of docs is definitely lacking, but perhaps it will inspire you in some way.


This comment has been minimized.

Copy link

@gastonmorixe gastonmorixe commented Jan 10, 2020

@FredyC awesome! will check it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment