useEffect to check for update of useState

I have a problem that useState whenever is updated calls previous value
Is there any way to use useEffect to check it for update?

  const [thisButtomSelected, setThisButtomSelected] = useState({
    thisVal: 0,
    thisIndex: 0,
  })
   const onClick = e => {  
    setThisButtomSelected({ thisVal: e.currentTarget.value, thisIndex: e.currentTarget.id });
  }

  <li id="list" key={item.id}>
    <button
      value={item.value}
      id={index}
      className={isEqual(thisButtomSelected, { thisVal: item.value, thisIndex: index }) 
        ? 'button-selected' : 'button'
      }
      onClick={onClick}
    >
      {item.displayValue}
    </button>
</li>

>Solution :

Your question is not really clear about what you want to do, but having useEffect be aware of state change could be done like so :

useEffect(()=>{
 // do things

},[thisButtomSelected])

The function inside useEffect will get executed whenever thisButtomSelected changes and also when the component render the first time.

Leave a Reply