React - Intermediate Flashcards
When you update state does this happen straight away?
No state updates are asynchronous.
How do you update state that is an array using its previous state?
You can’t alter previous state directly so you have to return an entirely new array from the state setter’s inner function. Creating the new array can be done using square brackets and placing the contents of the previous state array inside, along with any new elements you want to add.
return […prevState, ‘new item’];
The spread operator is used to place the contents of the old array inside the new array.
How do you update state that is an object using it’s previous state?
We can’t alter state directly so have to return a new object from the state setter’s inner function. The spread operator prints the existing properties and then you just declare the properties you want to overwrite.
return {…prevState, name: ‘Thomas’}
The second ‘name’ property will overwrite the old name property.
What is the golden rule for accessing previous state?
Don’t access previous state directly. Return a completely new variable from the state setters inner function.
What does mutable mean in programming?
“Mutable” in programming refers to anything that can change during the running of a program. The dictionary definition is “liable or subject to change or alteration”. The opposite would be “Immutable” (i.e. something that cannot change).