Skip to content

Commit 80f64ca

Browse files
committed
perf: ⚡️ cache field
1 parent d9f75bb commit 80f64ca

File tree

1 file changed

+27
-24
lines changed

1 file changed

+27
-24
lines changed

src/index.ts

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ const useForm: UseForm = <T>(intial: Partial<T>) => {
6161

6262
const fieldOptions = {}
6363

64+
const fields = {}
65+
6466
const [hooksState, setState] = useState({
6567
fields: Object.keys(initialData).reduce((prev, key) => {
6668
return {
@@ -72,8 +74,6 @@ const useForm: UseForm = <T>(intial: Partial<T>) => {
7274
options: {},
7375
})
7476

75-
// const fieldOptions = fieldOptionsRef.current
76-
7777
let state = hooksState
7878

7979
const dispatch = function(type, payload) {
@@ -161,29 +161,32 @@ const useForm: UseForm = <T>(intial: Partial<T>) => {
161161

162162
const field = <K extends keyof T>(name: K, option?: FieldOption) => {
163163
setOption(name, option)
164-
return {
165-
get value() {
166-
const value = get(state, `fields.${name}.value`)
167-
return value === undefined ? getResetValue(option && option.type) : value
168-
},
169-
set value(value) {
170-
this.onChange(value)
171-
},
172-
onChange (event: Event | any) {
173-
const value = event.target ? event.target.value : event
174-
const newState = updateField(name, {
175-
value,
176-
touched: true
177-
})
178-
innerValidate(noop, [name], 'change', newState)
179-
},
180-
onBlur() {
181-
const newState = updateField(name, {
182-
touched: true
183-
})
184-
innerValidate(noop, [name], 'blur', newState)
185-
},
164+
if(!fields[name as string]) {
165+
fields[name as string] = {
166+
get value() {
167+
const value = get(state, `fields.${name}.value`)
168+
return value === undefined ? getResetValue(option && option.type) : value
169+
},
170+
set value(value) {
171+
this.onChange(value)
172+
},
173+
onChange (event: Event | any) {
174+
const value = event.target ? event.target.value : event
175+
const newState = updateField(name, {
176+
value,
177+
touched: true
178+
})
179+
innerValidate(noop, [name], 'change', newState)
180+
},
181+
onBlur() {
182+
const newState = updateField(name, {
183+
touched: true
184+
})
185+
innerValidate(noop, [name], 'blur', newState)
186+
},
187+
}
186188
}
189+
return fields[name as string]
187190
}
188191

189192
return [

0 commit comments

Comments
 (0)