In React applications, the useEffect hook is a powerful tool for handling side effects and component lifecycle events. However, sometimes you might find it useful to know which specific props triggered an useEffect callback. This can be particularly handy when dealing with optimizations or debugging. In this blog post, we'll explore a custom hook named useWhichPropsChanged that allows you to easily identify the props responsible for triggering an useEffect call.
The Custom Hook - useWhichPropsChanged:
import React from 'react';
const useWhichPropsChanged = (initialProps) => {
const propsRef = React.useRef(initialProps);
return (currentProps) => {
const pKeys = Object.keys(propsRef.current);
pKeys.forEach((ele) => {
if (propsRef.current[ele] !== currentProps[ele]) {
console.log(`prop ${ele} has changed...`);
}
});
propsRef.current = currentProps;
};
};
Using the Hook in a Component:
import React, { useEffect } from 'react';
const Component = (props) => {
const { propsRequiredForSomeApiCall } = props;
const whichPropsChanged = useWhichPropsChanged(propsRequiredForSomeApiCall);
useEffect(() => {
whichPropsChanged(propsRequiredForSomeApiCall);
// Perform some API call or other side effects
}, [propsRequiredForSomeApiCall]);
return <></>;
};
How It Works:
The useWhichPropsChanged hook utilizes React's useRef to store a reference to the previous props. The returned function takes the current props as an argument and iterates over the keys of the stored props. If the current value of a prop differs from the stored value, a log message is generated indicating which prop has changed. After processing, the stored props are updated to match the current props, allowing for future comparisons.
Top comments (0)