Skip to content

fix(useForm): Use memoized form instance of lazy getter. #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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