DEV Community

Discussion on: TIL: You can watch for nested properties changing in React's useEffect() hook

Collapse
 
gabrielmlinassi profile image
Gabriel Linassi • Edited

It's a fine solution if the object property always exists however if the property is not present at some point you get a reference error. My workaround in this scenario is to check if prop exists inside the hook

useEffect(()=> {
if (values?.age) {
ageChangeSideEffect(values.age);
}
}, [values])

Collapse
 
abe profile image
Abraham J Gonzalez B

I think is better to use values?.age as a dependency, to avoid to listen all changes in values.

Collapse
 
milichev profile image
Vadym Milichev

There is no change listening in values because it's an object which is checked for equality by reference. If values is passed to the component as a property and its value is composed as a plain inline object, it will be a new value on each render.