Skip to content

Better referential equality in useField #65

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
36 changes: 20 additions & 16 deletions src/useField.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fieldSubscriptionItems } from 'final-form'
import { useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'

export const all = fieldSubscriptionItems.reduce((result, key) => {
result[key] = true
Expand Down Expand Up @@ -50,22 +50,26 @@ const useField = (name, form, validate, subscription = all) => {
)
let { blur, change, focus, value, ...meta } = state
delete meta.name // it's in input
return {
input: {
const onBlur = useCallback(() => blur(), [blur])
const onChange = useCallback(event => change(eventValue(event)), [change])
const onFocus = useCallback(() => {
if (focus) {
focus()
} else {
autoFocus.current = true
}
}, [focus])
const input = useMemo(
() => ({
name,
value: value === undefined ? '' : value,
onBlur: () => state.blur(),
onChange: event => state.change(eventValue(event)),
onFocus: () => {
if (state.focus) {
state.focus()
} else {
autoFocus.current = true
}
}
},
meta
}
onBlur,
onChange,
onFocus,
value: value === undefined ? '' : value
}),
[name, onBlur, onChange, onFocus, value]
)
return { input, meta }
}

export default useField