I have the following controlled component set up using react-hook-forms.
<Controller
control={control}
name={"test"}
render={({ field: { onChange, value, name } }) => (
<Dropdown
name={name}
value={value}
handleChange={onChange}
options={foodCategories()}
/>
)}
/>
I want to call a debounce and and I tried doing the following:
handleChange={debounce(onChange, 500)}
but I keep getting errors throw:
This synthetic event is reused for performance reasons, Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable,
How can I call debounce on a controlled react hook form component?
In such situations, I use the following piece of code:
Custom input field:
const TextInput = ({ name, setValueDebounce }: { name: string; setValueDebounce: (value: string) => void }) => {
const handleTyping = useCallback(
debounce((value) => {
if (setValueDebounce) setValueDebounce(value);
}, 300),
[],
);
return (
<Controller
name={name}
render={({ field: { value, onChange, ...fieldProps } }) => (
<input
id={name}
value={value || ''}
onChange={(e) => {
onChange(e.target.value);
handleTyping(e.target.value);
}}
{...fieldProps}
/>
)}
/>
);
};
Where name is the property name provided in form, and setValueDebounce is the debounce function, which triggers after 300ms delay
<TextInput
name="name"
setValueDebounce={(value: string) => console.log(value)}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With