TechS
TechS

Reputation: 177

react hook form - watch vs onchange , which one would be the right approach

I am using watch,setValue and getValues to update one dropdown selected value based on another dropdown selected value. It can be also done using dropdown list's onChange so, onChange, setValue and getValues so no need to use of watch. Can you please guide, watch is performance cost then using onChange or it will be fine with watch how its implemented below (without onChange).

const dropdownList_1_watch_value = watch(dropdownList_1);

    useEffect(()=>{
    if (dropdownList_1_watch_value !== 'specificValue') && getValues(dropdownListControlName) !== defaultValue)
    {
    setValue(another_dropdownListControlName, defaultValue);
    }},[dropdownList_1_watch_value]);

return (
<>
 // list of dropdown list components and other controls
</>

);

Upvotes: 1

Views: 4521

Answers (1)

Thomas K.
Thomas K.

Reputation: 139

Regarding performance there shouldn't be much of a difference between those to.

I will cite from a blog post:

React Watcher should be used sparingly, in cases where you can't really solve the problem any other way. In most cases, where you need to do something when some prop changes, you don't really need it. Why? Because in most cases you can usually trigger the event together with the action with caused the prop to be changed, e.g. when triggering a filtering change on a listing.

Full post: http://sborrazas.com/blog/react-watcher

Upvotes: 1

Related Questions