Skip to content

Commit f6bde38

Browse files
avocadowastakenerikras
authored andcommitted
fix(useForm): Use memoize form instance of lazy getter. (#25)
1 parent 31634df commit f6bde38

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/useForm.js

+15-13
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,25 @@ import { createForm, configOptions } from 'final-form'
33
import useFormState from './useFormState'
44
import shallowEqual from './internal/shallowEqual'
55

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+
617
const useForm = ({
718
subscription,
819
initialValuesEqual = shallowEqual,
920
...config
1021
}) => {
11-
const form = useRef()
22+
const form = useMemoOnce(() => createForm(config))
1223
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)
2325
const handleSubmit = useCallback(event => {
2426
if (event) {
2527
if (typeof event.preventDefault === 'function') {
@@ -29,7 +31,7 @@ const useForm = ({
2931
event.stopPropagation()
3032
}
3133
}
32-
return getForm().submit()
34+
return form.submit()
3335
}, [])
3436

3537
useEffect(() => {
@@ -56,7 +58,7 @@ const useForm = ({
5658
prevConfig.current = config
5759
})
5860

59-
return { ...state, form: getForm(), handleSubmit }
61+
return { ...state, form, handleSubmit }
6062
}
6163

6264
export default useForm

0 commit comments

Comments
 (0)