Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React array did not update despite using useEffect

I am trying to add an element into an array after I click the "click me" button.
I did a console log to make sure it went inside the function, but despite the function being call, nothing changes.

I also try using useEffect to check if my variable got update

useEffect(() => {
    console.log("cardData ", test);
  }, [test]);

Really need some advice on where did i go wrong

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my codesandbox link

>Solution :

The issue is that you directly mutate the test (test.unshift does mutate the test instance) and rendering does not happen since no reference change was detected (shallow reference is used when rendering happens).

Try this

  const onChange = () => {
    console.log("onChange");

    const testCopy = [...test];
    testCopy.unshift("4");
    setTest(testCopy);
  };

Code sandbox => https://codesandbox.io/s/dark-wildflower-lkf4u?file=/src/App.js:160-302

Another NOT working case can be given like below due to using the same instance reference (test).

  const onChange = () => {
    console.log("onChange");
    test.unshift("4");
    setTest(test);
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading