Skip to content

Instantly share code, notes, and snippets.

@anthowen
Created July 2, 2021 01:21
Show Gist options
  • Save anthowen/f60b765c53855ebded1b3b2cd537cd77 to your computer and use it in GitHub Desktop.
Save anthowen/f60b765c53855ebded1b3b2cd537cd77 to your computer and use it in GitHub Desktop.
The formik onChange solution. The one utility component you will be mostly looking for when using Formik
import { useRef } from 'react';
import PropTypes from 'prop-types';
import useDeepCompareEffect from 'use-deep-compare-effect';
import { useDebouncedCallback } from 'use-debounce';
import { useFormikContext } from 'formik';
const FormikOnChange = ({ delay, onChange }) => {
const { values } = useFormikContext();
const isFirstRun = useRef(true);
const debouncedOnChange = useDebouncedCallback(onChange, delay);
useDeepCompareEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
if (delay > 0) {
debouncedOnChange(values);
} else {
onChange(values);
}
}, [values]);
return null;
};
FormikOnChange.propTypes = {
delay: PropTypes.number, // ms
onChange: PropTypes.func.isRequired,
};
FormikOnChange.defaultProps = {
delay: 0,
};
export default FormikOnChange;
// Credit goes to @asologor
// https://github.com/formium/formik/issues/1633#issuecomment-597075634
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment