Skip to content

Commit 3225321

Browse files
avocadowastakenerikras
authored andcommitted
feat(useForm): Create form lazily. (#14)
* feat(useForm): Create form lazily. * fix(useForm): Use `getForm` in `useEffect`.
1 parent 6f1c9d7 commit 3225321

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/useForm.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,17 @@ export const all = formSubscriptionItems.reduce((result, key) => {
77
}, {})
88

99
const useForm = ({ subscription, ...config }) => {
10-
const form = useRef(createForm(config))
10+
const form = useRef()
11+
// https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
12+
const getForm = () => {
13+
if (!form.current) {
14+
form.current = createForm(config)
15+
}
16+
17+
return form.current
18+
}
1119
const [state, setState] = useState({})
12-
useEffect(() => form.current.subscribe(setState, subscription || all), [
20+
useEffect(() => getForm().subscribe(setState, subscription || all), [
1321
subscription
1422
])
1523
const handleSubmit = useCallback(event => {
@@ -21,10 +29,10 @@ const useForm = ({ subscription, ...config }) => {
2129
event.stopPropagation()
2230
}
2331
}
24-
return form.current.submit()
32+
return getForm().submit()
2533
}, [])
2634

27-
return { ...state, form: form.current, handleSubmit }
35+
return { ...state, form: getForm(), handleSubmit }
2836
}
2937

3038
export default useForm

0 commit comments

Comments
 (0)