1- import { ChangeEventHandler , useEffect , useState } from 'react' ;
1+ import { ChangeEventHandler , useState } from 'react' ;
22import isUndefined from 'lodash/isUndefined' ;
33
44interface ControlledValueReturnObject < T extends string > {
@@ -15,7 +15,7 @@ interface ControlledValueReturnObject<T extends string> {
1515 * A setter for the internal value.
1616 * Does not change the controlled value if the provided value has not changed.
1717 */
18- setInternalValue : React . Dispatch < React . SetStateAction < T > > ;
18+ setUncontrolledValue : React . Dispatch < React . SetStateAction < T > > ;
1919}
2020
2121/**
@@ -30,29 +30,22 @@ export const useControlledValue = <T extends string>(
3030) : ControlledValueReturnObject < T > => {
3131 const isControlled = ! isUndefined ( controlledValue ) ;
3232
33- // Keep track of state internally, initializing it to the controlled value
34- const [ value , setInternalValue ] = useState < T > ( controlledValue ?? ( '' as T ) ) ;
35-
36- // If the controlled value changes, update the internal state variable
37- useEffect ( ( ) => {
38- if ( ! isUndefined ( controlledValue ) ) {
39- setInternalValue ( controlledValue ) ;
40- }
41- } , [ controlledValue ] ) ;
33+ // Keep track of the uncontrolled value state internally
34+ const [ uncontrolledValue , setUncontrolledValue ] = useState < T > ( '' as T ) ;
4235
4336 // Create a change event handler that either updates the internal state
4437 // or fires an external change handler
4538 const handleChange : ChangeEventHandler < any > = e => {
4639 changeHandler ?.( e ) ;
4740 if ( ! isControlled ) {
48- setInternalValue ( e . target . value as T ) ;
41+ setUncontrolledValue ( e . target . value as T ) ;
4942 }
5043 } ;
5144
5245 return {
5346 isControlled,
54- value,
47+ value : isControlled ? controlledValue : uncontrolledValue ,
5548 handleChange,
56- setInternalValue ,
49+ setUncontrolledValue ,
5750 } ;
5851} ;
0 commit comments