user8006446
user8006446

Reputation: 475

Comparing two state variables in React

I'd like to compare two pieces of state in a React component, which are both set on the click of a button. My problem is that when the second button is clicked, the compare function is called straight away before the state is updated, so I continually get a 'no match'. Here's a breakdown of the code (this is a single button component - which is displayed several times through a forEach loop. There are two pieces of state - first and second - which are integers).

const handleSelection = (e) => {
    if (!first) {
        setFirst(e.target.dataset.id);
    } else if (!second) {
        setSecond(e.target.dataset.id);
        checkMatch();
    } else {
        setFirst(e.target.dataset.id);
        setSecond(undefined);
    }
}   

const checkMatch = () => {
    if(first === second) {
        console.log('match');
    } else {
        console.log('no match');
    }
}


return (
    <div className="grid-item">
        <button onClick={(e) => handleSelection(e)} data-id={item.number}>{item.number}</button>
    </div>
)

Upvotes: 0

Views: 3919

Answers (1)

Neeko
Neeko

Reputation: 1149

The useEffect hook can help you subscribe to any changes in your state as soon as one of the values passed as dependencies is updated.

So instead of having your checkMatch function, you could do:

useEffect(() => {
   if (first === second) {
      console.log('match');
   } else {
      console.log('no match');
   }
}, [first, second]);

In this example, first and second are the dependencies of your useEffect hook and will call the callback function (the first parameter of useEffect) any time one of these state variables has been updated.

Upvotes: 5

Related Questions