Listen for changes in Formik field using ref and useEffect

Viewed 2835

I'm trying to use the ref in Formik to let useEffect listen for changes in form field values. But when I run:

const formikRef = useRef(); // this gets passed to Formik's ref prop on component render

React.useEffect(() => {
    // do something
}, [formikRef.current.state.values.MyFormFieldName]);

It fails with this error: Cannot read property 'state' of undefined

I'm on Formik v1.3 and I can't directly access the Field component since I'm using a custom wrapper component (as part of an internal UI library) and it doesn't expose all the Field props.

EDIT:

I can do formikRef.current?.state.values.MyFormFieldName but that still doesn't cause useEffect to fire when MyFormFieldName changes.

1 Answers

You get the error because when the component initializes, the current property is null / undefined and you are trying to access a property (state) of it.

In addition, passing the hook to the dependency array seems to have not the effect you desire, in short it seems to have no effect:

React Hook useEffect has an unnecessary dependency: ‘formikRef.current’. Either exclude it or remove the dependency array. Mutable values like ‘contentRef.current’ aren’t valid dependencies because mutating them doesn’t re-render the component

A workaround for your problem (described at the end of the previously linked article) would be to save the ref in the state after initialization:

const App = (props) => {
  const [formik, setFormik] = React.useState();

  const formikRef = (node) => {
    if (node !== null) {
      setFormik(node.getBoundingClientRect().height);
    }
  };

  React.useEffect(() => {
    // do something
  }, [formik]);

  return (
    <div ref={formikRef}>
      <span>Hello Bro</span>
    </div>
  );
};

You can play with the example on Codepen.

Related