#React.useState() with array [Box challenge]

7 messages · Page 1 of 1 (latest)

vagrant whale
#

Hey! I tried writing code myself for this challenge [line 19 - 24],the changes are getting reflected in newSquares but the backgroundColor of squares isn't changing . I don't get the problem could anyone please explain!?

link: https://scrimba.com/scrim/c2aLnnCR
Thank you😇

Scrimba

Learn to code with interactive screencasts. Our courses and tutorials will teach you React, Vue, Angular, JavaScript, HTML, CSS, and more. Scrimba is the fun and easy way to learn web development.

gray glen
green ravine
#

Hey Landeri, you have to save the previous array like this by using using spread operator!

   setSquares(prevSquares =>{
            const newSquares = [...prevSquares]
            newSquares[id - 1].on = !newSquares[id - 1].on
            console.log(newSquares)
            return newSquares
        })
    }
#

by directly saving the array in the newSquares varaible does not save the updated array in it!

vagrant whale
#

Thanks a lot @green ravine!

But can I know what's the difference between the two?

green ravine
#

Yes sure, sorry for replying very late, super busy! yea so the difference between these two modifying state directly in the state setter function is not a good idea!
in this case:

//Is not a good practice
const newSquares = prevSquares

/*Reason: You have to save the instance of each updated state! */

//Is a good practice
const newSquares = [... prevSquares]

/*Reason: you are now saving all the previous array and the updated state! */

hope it make sense

vagrant whale
#

No problem! and Thank you for the clarification🙂