Home > Software design >  React: Can I find out what elements have been updated in an array state?
React: Can I find out what elements have been updated in an array state?

Time:11-26

If I have a React array state created with the useState hook, is it possible to somehow find out what elements have been updated? My intention is to run some code whenever the state updates, inside of a useEffect hook, but I would like to have access to the index(es) of the updated array elements. Is this possible?

CodePudding user response:

Yes you can but if the indexes are not changed.

You can hold your previous state and in your useEffect, iterate through your new array and check if the element at index i is equal to the corresponding element in previous state or not:

const [myArray, setMyArray] = useState([]);
const [myPreviousArray, setMyPreviousArray] = useState([]);

// Assume we have a function that updates the state
const handleArrayDataChange = (newValue) => {
  setMyPreviousArray([...myArray]);
  setMyArray(newValue);
}

useEffect(() => {
  myArray.forEach((item, index) => {
   if(JSON.stringify(item) !== JSON.stringify(myPreviousArray[index])) {
    // The item is updated
   }
  });
}, [myArray]);

CodePudding user response:

My intention is to run some code whenever the state updates, inside of a useEffect hook,

This can be done by passing downn the state in the dependecy array of useEffect.

const [nameArray, setNameArray] = useState([]);

useEffect(() => {
// things you want to do
},[nameArray]);
  • Related