skip to Main Content

The values from a dropdown is based on an API call whose array response is stored into a Zustand store. I have a useEffect that listens to when that Zustand store variable is no longer empty, it will automatically assign the first value in that array as the selected value in the form.

  const formik = useFormik()
  const store = useZustandStore()

  useEffect(() => {
    if (store.someSearchItems.length) {
      const initial = store.someSearchItems[0].value as string;

      formik.setFieldValue('LIST_VALUE', initial);
    }
  }, [store.someSearchItems]);

It does its job, however, I get the error React Hook useEffect has a missing dependency: 'formik'. Either include it or remove the dependency array. How do I workaround this lint issue without disabling it?

I tried including formik in the dependency array, but that executes the useEffect even if unrelated values inside the form is changed.

2

Answers


  1. You can do this:

    function listValue(){
        const initial = store.someSearchItems[0].value as string;
    
        formik.setFieldValue('LIST_VALUE', initial);
    }
    
      useEffect(() => {
        if (store.someSearchItems.length) {
         listValue();
        }
      }, [listValue, store.someSearchItems]);
    

    Alternatively, you can suppress the warning with this comment:
    // eslint-disable-next-line react-hooks/exhaustive-deps

    Although, you can read more on why it is dangerous here

     useEffect(() => {
        if (store.someSearchItems.length) {
          const initial = store.someSearchItems[0].value as string;
    
          formik.setFieldValue('LIST_VALUE', initial);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [store.someSearchItems]);
    
    Login or Signup to reply.
  2. The result of useFormik (your formik constant) changes on each render, because it contains the form values. However, setFieldValue (and other methods) are stable.

    Instead of using the entire formik object, destructure setFieldValue, and use it in the useEffect, and it’s dependencies.

    const { setFieldValue } = useFormik()
    const store = useZustandStore()
    
    useEffect(() => {
      if (store.someSearchItems.length) {
        const initial = store.someSearchItems[0].value as string;
    
        setFieldValue('LIST_VALUE', initial);
      }
    }, [store.someSearchItems, setFieldValue]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search