inertia icon indicating copy to clipboard operation
inertia copied to clipboard

useForm methods are not stable

Open JamesHemery opened this issue 3 years ago • 0 comments

Versions:

  • @inertiajs/inertia version: 0.11.1
  • @inertiajs/inertia-react version: 0.8.1

Describe the problem:

The methods exposed by the return of the useForm hook are not stable. At each rendering, they are new functions and thus new javascript references.

This is a problem when we want to use one of these methods (reset, setData, ...) with a useEffect, useCallback, useMemo.

These hooks (useEffect, useCallback, useMemo) make superficial comparisons (based on references) to know if they should be executed.

Note that all variables created within a component and used in one of these hooks must be indicated in its dependency table.

Steps to reproduce:

Use this code with an input or anything that will trigger a re-render and the useEffect will be executed at each render. While however it should be executed only when reset method changes.

    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
    });

    useEffect(() => {
       console.log('This will be executed at each render');
    }, [reset]);

Short term fix

Remove the method from dependencies array but it's a bad thing.

    useEffect(() => {
       console.log('This will be executed at each render');
    }, []);

Long term fix

Memoize useForm returned methods with useCallback.

If you're ok (@reinink @claudiodekker) I can make a PR, but I have the impression that they are currently no reviewed?

JamesHemery avatar Oct 16 '22 13:10 JamesHemery