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

useState is not re-rendering with push and pop on an array state

I’m attempting to update the usersData variable created using useState so that anytime someone clicks on add user, a data object is added to the beginning of usersData, but the problem is that it only works with spread operators and not with push, pop, or unshift operations, as seen in the code below.

The code below is functioning great, and it updates and re-renders everytime usersData changes.

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    const dataUpdated = [data, ...usersData];
    setUsersData(dataUpdated);
  };

However, dataUpdated has the same data as above code, the following code does not re-renders the page.

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    let dataUpdated = usersData;
    dataUpdated.unshift(data);
    setUsersData(dataUpdated);
  };

>Solution :

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

The second attempt, witch is below,

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    let dataUpdated = usersData;
    dataUpdated.unshift(data);
    setUsersData(dataUpdated);
  };

do not re-render because for React nothing has changed, since you are giving the same reference (dataUpdated and usersData have the same reference). Objects and Arrays, behave this way, every time you need to update in order to have a re-render, you need to create a new reference. And the spread operator do create a new reference, this is why your first attempt witch below is is working.

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    const dataUpdated = [data, ...usersData];
    setUsersData(dataUpdated);
  };
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