final-form / react-final-form

🏁 High performance subscription-based form state management for React
https://final-form.org/react
MIT License
7.39k stars 481 forks source link

Infinite loop due initialValue prop #686

Open komsikov opened 4 years ago

komsikov commented 4 years ago

👋 Hey, thanks for final-form first of all

bug report

What is the current behavior?

When I pass as an argument a deep object to initialValue prop i get maximum update depth error.

What is the expected behavior?

I expect to exclude maximum update depth error, how can i fix it?

Correction: I need to deepEqual of form state instead of shallowEqual, this is very critical for me

Sandbox Link

See the SandBox

tokenvolt commented 4 years ago

I am seeing the same issue as well, while passing the same value as initialValues in a Form component works as expected.

ImADrafter commented 4 years ago

This is still happening with latest versions. I made this codesandbox wich is simpler

bwindsor commented 3 years ago

If the initial value is an object or array, a new object is created on each rerender. This means that the initialValue prop changes, even though you didn't intend it to. So instead of

initialValue={["Jack"]}

you should use

const initialValue = React.useMemo(() => ["Jack"], []);
<Field initialValue={initialValue}>

This ensures that the same object is passed to initialValue each time and prevents an infinite loop.