1- import { useCallback , useEffect , useRef , useState } from 'react'
1+ import { useCallback , useEffect , useRef , useState , memo } from 'react'
22
33enum TextInputSize {
44 XS = 'xs' ,
@@ -7,6 +7,7 @@ enum TextInputSize {
77 LG = 'lg' ,
88 XL = 'xl' ,
99}
10+
1011interface TextInputProps {
1112 id ?: string
1213 value : string
@@ -28,7 +29,15 @@ interface TextInputProps {
2829 max ?: number
2930}
3031
31- export function TextInput ( {
32+ const sizes : Record < TextInputSize , string > = {
33+ [ TextInputSize . XS ] : 'input-xs' ,
34+ [ TextInputSize . SM ] : 'input-sm' ,
35+ [ TextInputSize . MD ] : 'input-md' ,
36+ [ TextInputSize . LG ] : 'input-lg' ,
37+ [ TextInputSize . XL ] : 'input-xl' ,
38+ }
39+
40+ export const TextInput = memo ( function TextInput ( {
3241 onChange,
3342 value,
3443 placeholder,
@@ -48,30 +57,27 @@ export function TextInput({
4857 min,
4958 max,
5059} : TextInputProps ) {
51- const sizes : Record < TextInputSize , string > = {
52- [ TextInputSize . XS ] : 'input-xs' ,
53- [ TextInputSize . SM ] : 'input-sm' ,
54- [ TextInputSize . MD ] : 'input-md' ,
55- [ TextInputSize . LG ] : 'input-lg' ,
56- [ TextInputSize . XL ] : 'input-xl' ,
57- }
5860 const [ localValue , setLocalValue ] = useState ( value )
5961 const debounceTimerRef = useRef < NodeJS . Timeout | null > ( null )
6062
6163 useEffect ( ( ) => {
62- setLocalValue ( value )
63- } , [ value ] )
64+ if ( debounce ) {
65+ setLocalValue ( value )
66+ }
67+ } , [ value , debounce ] )
6468
6569 const handleChange = useCallback (
6670 ( e : React . ChangeEvent < HTMLInputElement > ) => {
6771 const newValue = e . target . value
68- setLocalValue ( newValue )
6972
7073 if ( ! debounce ) {
74+ // بدون هیچ تاخیری مستقیم onChange را صدا بزن
7175 onChange ( newValue )
7276 return
7377 }
7478
79+ setLocalValue ( newValue )
80+
7581 if ( debounceTimerRef . current ) {
7682 clearTimeout ( debounceTimerRef . current )
7783 }
@@ -85,13 +91,24 @@ export function TextInput({
8591 } ,
8692 [ onChange , debounce , type , debounceTime ]
8793 )
94+
95+ useEffect ( ( ) => {
96+ return ( ) => {
97+ if ( debounceTimerRef . current ) {
98+ clearTimeout ( debounceTimerRef . current )
99+ }
100+ }
101+ } , [ ] )
102+
103+ const displayValue = debounce ? localValue : value
104+
88105 return (
89106 < input
90107 ref = { ref }
91108 id = { id }
92109 type = { type }
93110 name = { name }
94- value = { localValue }
111+ value = { displayValue }
95112 disabled = { disabled }
96113 onFocus = { onFocus }
97114 onKeyDown = { onKeyDown }
@@ -107,4 +124,6 @@ export function TextInput({
107124 max = { max }
108125 />
109126 )
110- }
127+ } )
128+
129+ TextInput . displayName = 'TextInput'
0 commit comments