useEffect update only when some fields in states have been changed

Viewed 1109

Suppose that I have the following state

const [states, setStates] = useState([
      {name: '', age: '', amount: ''},
      {name: '', age: '', amount: ''},
]);
const total = 0;

I wish to use useEffect to update only when age fields are changed to calculate the amount fields. And then update the total field based on the amount fields changed. How do I do that? In this example, I have small number of array with three fields, but in reality, I have a big array with a lot of fields, so I don't want to use useEffect when any fields in states change.

1 Answers

The short answer is that you can't do that - the useEffect hook doesn't provide the ability to keep track of specific object properties inside of an array.

You'd have to keep track of another piece of state that will change if any of the age properties change, which will trigger the useEffect that has that piece of state in the dependency array.

const [states, setStates] = React.useState([...])
const [lastAgeUpdatedAt, setLastAgeUpdatedAt] = React.useState(null)
// const total = 0; // by the way, this looks like something that 
                    // should also be stored in a state,
                    // the below would be more appropriate
const [total, setTotal] = React.useState(0)

const handleUpdateAge = () => {
  setStates(...)
  if (ageUpdatesAvailable) {
    setLastAgeUpdatedAt(Date.now())
  }
}


React.useEffect(() => {
  const total = states.reduce(
    (accumulator, item) => accumulator + parseInt(item.age, 10), 
    0
  )
  setTotal(total)
}, [lastAgeUpdatedAt])
Related