Search code examples
reactjsuse-effectformikusecallback

React Hook useCallback has a missing dependency or Maximum update depth exceeded


In a useEffect , I check if an object exists,

if the object exists I call a useCallBack function which will fill in the values of a form via formik

Here is the problem :

1- if I do not fill in the formDef in the dependencies of useCallBack, I get a message telling me

 React Hook useCallback has a missing dependency: 'formDef'. 

and in this case I cannot build my branch following this error.

2 - if I fill in the formDef in the dependencies of useCallBack, the function loops infinitely, with the following error message:

 Warning: Maximum update depth exceeded. This can happen when a component calls
 setState inside useEffect, but useEffect either doesn't have a dependency array,
`enter code here` or one of the dependencies changes on every render.

useCallBack:

 const InitialiseTypeStorage = useCallback(() => {
   if (type) {
    for (const [key, value] of Object.entries(type.type)) {
      formDef.setFieldValue(key, value);
      }
   }
 }, [type]);

useFormik :

 const formDef = useFormik({
   initialValues: formTypedValues,
   validateOnMount: true,
   validationSchema,
   enableReinitialize: true,
   validateOnChange: true,
   onSubmit: (values) => handleMappingType(values),
 });

useEffect :

  useEffect(() => {
   InitialiseTypeStorage();
  }, [InitialiseTypeStorage]);

Is there a solution to avoid these two error messages?


Solution

  • In this case, simply destructure the formik can get rid of the warning.

     const { setFieldValue } = formDef;
    
     const InitialiseTypeStorage = useCallback(() => {
       if (type) {
        for (const [key, value] of Object.entries(type.type)) {
          setFieldValue(key, value);
          }
       }
     }, [type, setFieldValue]);