The new React API includes useEffect()
, the second argument of which takes an Object
which React diffs to see if the component updated.
e.g.
useEffect(
() => {
const subscription = props.source.subscribe();
return () => {
subscription.unsubscribe();
};
},
[props.source],
);
where [props.source]
is the argument in question.
My question is: can I define a custom function to run to check if the prop has changed?
I have a custom object and React can't seem to tell when it has changed.
Credit for this answer goes to @Tholle use object in useEffect 2nd param without having to stringify it to JSON
Why use
useRef
instead ofuseState
By using the function returned from useState the component will be re-rendered, which is not desired in this case
AFAIK it's not currently possible. There are some workarounds:
1) Do deep comparison manually inside
useEffect
. To store the prev. value you may useuseState
or, even better,useRef
as demonstrated here: https://overreacted.io/a-complete-guide-to-useeffect/2) Hashing with
JSON.stringify(props.source)
. Can be fine, if the data is not too big. Note thatstringify
may produce inconsistent results (keys in objects changing order will change the output).3) Hashing with
md5(props.source)
(or some other quick/light hashing). More realiable yet slower than the previous.