Skip to content

Commit

Permalink
fix(useForm): Use memoize form instance of lazy getter. (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
avocadowastaken authored and erikras committed Mar 4, 2019
1 parent 31634df commit f6bde38
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions src/useForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,25 @@ import { createForm, configOptions } from 'final-form'
import useFormState from './useFormState'
import shallowEqual from './internal/shallowEqual'

// https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
const useMemoOnce = factory => {
const ref = useRef()

if (!ref.current) {
ref.current = factory()
}

return ref.current
}

const useForm = ({
subscription,
initialValuesEqual = shallowEqual,
...config
}) => {
const form = useRef()
const form = useMemoOnce(() => createForm(config))
const prevConfig = useRef(config)

// https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
const getForm = () => {
if (!form.current) {
form.current = createForm(config)
}

return form.current
}
const state = useFormState(getForm(), subscription)
const state = useFormState(form, subscription)
const handleSubmit = useCallback(event => {
if (event) {
if (typeof event.preventDefault === 'function') {
Expand All @@ -29,7 +31,7 @@ const useForm = ({
event.stopPropagation()
}
}
return getForm().submit()
return form.submit()
}, [])

useEffect(() => {
Expand All @@ -56,7 +58,7 @@ const useForm = ({
prevConfig.current = config
})

return { ...state, form: getForm(), handleSubmit }
return { ...state, form, handleSubmit }
}

export default useForm

0 comments on commit f6bde38

Please sign in to comment.