Imperative update
Last modified on Mon 11 Apr 2022

When you are working with refs you have control over the update phase but you don't have a way to trigger it imperatively. But, if you still need to trigger an update imperatively, you can use a custom useUpdate hook.

Note: This example demonstrates how react-hook-form works internally.

const updateReducer = (num: number): number => (num + 1) % 1_000_000;

const useUpdate = () => {
  const [, update] = useReducer(updateReducer, 0);

  return update;
}

// Large form
// This is how react-hook-form works, in a nutshell
const Form: FC = () => {
  const formRef = useRef();

  if (!formRef.current) {
    formRef.current = {
      name: "",
      surname: "",
      // ...many fields
    };
  }

  const update = useUpdate();

  const register = useCallback((input) => {
    input?.addEventListener(
      "input",
      () => (formRef.current[input.name] = input.value)
    );
  }, []);

  const submit = useCallback(
    (event) => {
      event.preventDefault();
      // triggers update and renders the form data
      update();
    },
    [update]
  );

  return (
    <form onSubmit={submit}>
      <div>Form Data: {JSON.stringify(formRef.current)}</div>
      <input name="name" ref={register} />
      <input name="surname" ref={register} />
      // ...many fields
      <input type="submit" />
    </form>
  )
}