@@ -3,23 +3,25 @@ import { createForm, configOptions } from 'final-form'
3
3
import useFormState from './useFormState'
4
4
import shallowEqual from './internal/shallowEqual'
5
5
6
+ // https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
7
+ const useMemoOnce = factory => {
8
+ const ref = useRef ( )
9
+
10
+ if ( ! ref . current ) {
11
+ ref . current = factory ( )
12
+ }
13
+
14
+ return ref . current
15
+ }
16
+
6
17
const useForm = ( {
7
18
subscription,
8
19
initialValuesEqual = shallowEqual ,
9
20
...config
10
21
} ) => {
11
- const form = useRef ( )
22
+ const form = useMemoOnce ( ( ) => createForm ( config ) )
12
23
const prevConfig = useRef ( config )
13
-
14
- // https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
15
- const getForm = ( ) => {
16
- if ( ! form . current ) {
17
- form . current = createForm ( config )
18
- }
19
-
20
- return form . current
21
- }
22
- const state = useFormState ( getForm ( ) , subscription )
24
+ const state = useFormState ( form , subscription )
23
25
const handleSubmit = useCallback ( event => {
24
26
if ( event ) {
25
27
if ( typeof event . preventDefault === 'function' ) {
@@ -29,7 +31,7 @@ const useForm = ({
29
31
event . stopPropagation ( )
30
32
}
31
33
}
32
- return getForm ( ) . submit ( )
34
+ return form . submit ( )
33
35
} , [ ] )
34
36
35
37
useEffect ( ( ) => {
@@ -56,7 +58,7 @@ const useForm = ({
56
58
prevConfig . current = config
57
59
} )
58
60
59
- return { ...state , form : getForm ( ) , handleSubmit }
61
+ return { ...state , form, handleSubmit }
60
62
}
61
63
62
64
export default useForm
0 commit comments