Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Mutating value in a React state object

I feel really stupid for asking such a simple question like this, but for some reason I forgot how to change the value in a React state object. For example:

const initialState = {
   likes: 100,
   dislikes: 25,
   isLiked: false,
   isDisliked: false
}

const [data, setData] = useState(initialState)

const handleLikes = e => {
    if (data.isLiked) {
        setData({ ...data, likes: data.likes - 1 });
    } else {
        setData({ ...data, likes: data.likes + 1 });
    }

    setData({ ...data, isLiked: !data.isLiked })
}

<button className={`like-button ${data.isLiked ? 'liked' : ''}`} onClick={handleLikes}>Like | <span className='likes-counter'>{data.likes}</span></button>

The confusing part, the part that made me ask this question, is the likes: data.likes + 1 part. When I click the button, it adds/removes the className as intended, but the value never changes. I know this is such a simple thing but I have spent a while on this.

What is wrong with the likes: data.likes + 1?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The two subsequent setData calls end up "overwriting" each other since the data captured by your handleLikes will not have changed after you call setData.

You'll want to use the functional form of setState to be able to reliably look at the current value (even when asynchronous modifications are in queue, then return a new value based on it:

const handleToggleLikes = (e) => {
  setData((data) =>
    data.isLiked
      ? { ...data, likes: data.likes - 1 }
      : { ...data, likes: data.likes + 1 },
  );
  setData((data) => ({ ...data, isLiked: !data.isLiked }));
};

You can do both of these modifications in one invocation:

const handleToggleLike = e => {
    setData(data => ({
        ...data,
        likes: data.likes + (data.isLiked ? -1 : 1),  // decrease if previously liked
        isLiked: !data.isLiked,
    }));
}
about 4 years ago · Juan Pablo Isaza Report

0

There are two ways to use a setState function to update the state object:

  1. Pass it the new state object (which is what you are doing in your code)
  2. Pass it a callback function that takes the current state object as argument, uses it to create the new state object, and returns the new state object.

Whenever you want to use the current state object to create a new state object, you must use the second way. In your case, your code:

setData({...data, likes: data.likes - 1})

uses the current state object (data) to create the new state object. So you must use a callback instead, like this:

setData((cur_data)=>({...cur_data, likes: cur_data.likes-1}))

Note that I am using the arrow syntax in the callback function to return the new state object.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!