Detect Function If Being Called In Another Component in React

I have this function called handleSelectProduct in ProductComponent and I wanted to detect it in ProductDetailsComponent. If handleSelectProduct is called in ProductComponent, then I want to run a certain function in ProductDetailsComponent using useEffect.

ProductComponent

const ProductComponent = () => {
  const [selectedProduct, setProduct] = useState(null);

  const handleSelectProduct = (event) => {
    setProduct(event.target.value);
  };

  return (
    <div>
      <Select
        value={selectedProduct}
        onChange={(e) => handleSelectProduct(e)}
      >
        {(products || []).map(({ id, name }) => (
          <MenuItem value={id}>{name}</MenuItem>
        ))}
      </Select>
      <ProductDetailsComponent handleSelectProduct={handleSelectProduct} />
    </div>
  );
};

export default ProductComponent;

ProductDetailsComponent

const ProductDetailsComponent = ({ handleSelectProduct }) => {
  useEffect(() => {
    handleSelectProduct ? formik.setFieldValue("productInfo", "") : null;
  }, [handleSelectProduct]);
};

export default ProductDetailsComponent;

Answer

If handleSelectProduct is called in ProductComponent, then I want to run a certain function in ProductDetailsComponent

I don’t think that’s exactly what you really want. If the components were that tightly coupled, you should use just a single component. The ProductDetailsComponent behaviour should depend only on its props and its internal state.

What you really want is to call a certain function in ProductDetailsComponent whenever the selected product changes. You can do that, as you already noticed, using useEffect – but with the product as a dependency. You just have to pass the selectedProduct as a prop to the component instead of the handleSelectProduct function.

const ProductComponent = () => {
  const [selectedProduct, setProduct] = useState(null);

  return (
    …
    <ProductDetailsComponent selectedProduct={selectedProduct} />
  );
};

const ProductDetailsComponent = ({ selectedProduct }) => {
  useEffect(() => {
    if (selectedProduct) formik.setFieldValue("productInfo", "");
  }, [selectedProduct]);
};