1

I currently have two arrays which updates based on the onClick event. I want to keep track of this array updates through useMemo ,I want to know which array is getting updated on every click but I want to execute separate function for each array when they are clicked , now I can see code inside useMemo is getting executed for both the click. how to achieve this.

Please refer to code here

import { useEffect, useMemo, useState } from "react";
import "./styles.css";

export default function App() {
  const [array1, setArray1] = useState([]);
  const [array2, setArray2] = useState([]);

  useMemo(() => {
// execute a certain function only when array1 is changed and vis versa
    console.log(array1);
  }, [array1, array2]);
  return (
    <div className="App">
      <h3>on button click I want log output when only "array1" is pressed </h3>
      <button onClick={() => setArray1([1])}>array1</button>
      <button onClick={() => setArray2([2])}>array2</button>
    </div>
  );
}

4
  • Shouldn't you use useEffect instead of memo since you are not memoizing anything and just want code to run? Commented Nov 17, 2022 at 11:10
  • I see but use effect also yield same results Commented Nov 18, 2022 at 4:01
  • Yes, that is the first thing. And with useEffect this question definitely has duplicates Commented Nov 18, 2022 at 4:46
  • stackoverflow.com/questions/55187563/… this helps? Commented Nov 18, 2022 at 4:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.