I have a component which passes an object as a prop to its children, as well as a function to update this object. Now, I've noticed in one of the children that reading a nested property of the prop (obj.nested.property) object always returns the initial value as it is on mount, although the prop (obj) is updated successfully - I can see this in react dev tools, and also from the useEffect console.log
Here's the structure:
const Parent = () => {
const obj = useSelector(config);
const setObj = (newObj) => {
// update obj code
}
return (
<Child obj={obj} onUpdate={setObj}/>
)
}
const Child = ({ obj, onUpdate }) => {
useEffect(() => {
console.log(obj.nested.property);
// here everything is correct. Every time the obj is updated, this logs the new
// obj.nested.property value
}, [obj])
const onBlur = (newValue) => {
if (newValue !== obj.nested.property) {
// here, after you change the value once, and then just click inside the input
// and blur, this condition is always true, because obj.nested.property keeps the
// value as it was on mount
onUpdate(newValue)
}
}
return (
<Input value={obj.nested.property} onBlur={onBlur}/>
)
}