Code example:
useEffect(() => {
//I want to know which was the variable which made the useffect run. var1 or var2. how can I?
}, [var1, var2]);
which dependency was used to make it run?
The easiest way to achieve the desired result without third-party libraries and a lot of code is to split useEffect into two useEffect hooks and one handler.
const handler = () => {
// ...some logic
};
useEffect(() => {
// var1 has been changed
handler();
}, [var1]);
useEffect(() => {
// var2 has been changed
handler();
}, [var2]);
Use useRef to keep the previous state and then compare the results.
const prevVar1 = useRef();
const prevVar2 = useRef();
useEffect(() => {
if(prevVar1.current !== var1) {
// var1 has been changed
}
if(prevVar2.current !== var2) {
// var2 has been changed
}
// and update the previous state
prevVar1.current = var1;
prevVar2.current = var2;
// ...some logic
}, [var1, var1]);
Or use the use-what-changed library
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