Necessary to use arrow function while changing the object using React.useState?

Hello everyone, beginner here :wave:
In the module Learn React > Meme Generator > Project: Refactor State, we have a meme state of an object where one of the properties is randomImage. The challenge is to update the randomImage property in the object. The meme state:
const [meme, setMeme] = React.useState({
topText: “”,
bottomText: “”,
randomImage: “http://i.imgflip.com/1bij.jpg
})

The soulution is
setMeme(prevMeme => ({
…prevMeme,
randomImage: [updated url]
}))

Now, I understand the solution but what I don’t understand is why are we using arrow function here when we can directly feed the object with all properties and simply update the radomImage property? The solution that gives the same result:
setMeme({
topText: “”,
bottomText: “”,
randomImage: [updated url]
})

Is there any issue with this approach other than repetitive code? or will it cause issue when we are dealing with larger development?
Thanks for your time!

Hey @sks98, great to hear you’re learning with us! I’m going to tag our React teacher @bobziroll here for more clarification incase I’ve missed some things.

From my experience, the main difference in using the arrow function versus directly declaring the properties is that it keeps the data state consistent and decreases risk of errors. The arrow function carries and keeps all existing properties and push them into the next code logic.

setMeme({
  topText: "",  // Always sets to empty
  bottomText: "",  // Always sets to empty
  randomImage: ["updated URL"]  // Only this needs to change
})

^ This method works but always resets topText and bottomText to empty strings, which might not be what you want if those fields could have had some text.

setMeme(prevMeme => ({
  ...prevMeme,  // Keeps all existing properties as they are
  randomImage: ["updated URL"]  // Only updates the image URL
}))

^ This way, you only update the image URL, and all other properties like topText and bottomText keep their current values. So only the image URL and leave everything else as it is.

Once your code base gets larger and more data is involved, it’s easier to just carry their states through your code without directly declaring it over and over. Plus, in large code bases, these data states will have a lot of state changes so it’s easier to keep track of their states by using the arrow function and pushing their states rather than redeclaring it.