Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created October 17, 2021 23:59
Show Gist options
  • Save andycarrell/c2da17c51751da73a54fb33d25e81dcd to your computer and use it in GitHub Desktop.
Save andycarrell/c2da17c51751da73a54fb33d25e81dcd to your computer and use it in GitHub Desktop.
import { useCallback, useLayoutEffect, useRef } from "react";
/**
* Returns a constant reference to a callback which can be safely added
* to dependency arrays without triggering the effect or memoization.
* Maintains an up to date copy of the provided function to avoid
* referencing stale state/props at calltime.
*/
const useEventCallback(fn) {
const ref = useRef(fn);
// copy a ref to the callback scoped to the current state/props on each render
useLayoutEffect(() => {
ref.current = fn;
});
return useCallback((...args) => ref.current(...args), []);
}
/**
* Simple utility over Formik's setValues.
* Leverages setValues' callback to apply patch.
* See: https://formik.org/docs/api/formik
*/
const usePatchValues = (form) => {
const { setValues } = form;
const patchValues = useCallback(
(patch) => setValues((values) => ({ ...values, ...patch })),
[setValues],
);
return { patchValues, ...form };
};
/**
* Simple utility over Formik's setErrors.
* Merges a 'patch' into errors object
* See: https://formik.org/docs/api/formik
*/
const usePatchErrors = (form) => {
const { setErrors, errors } = form;
const patchErrors = useEventCallback((patch) => setErrors({ ...errors, ...patch }));
return { patchErrors, ...form };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment