35
loading...
This website collects cookies to deliver better user experience
let newState = {
...oldState,
field1: {
...oldState.field1,
field2: "someNewValue"
},
}
field2
value by creating a new state and setting a new value to field2
. The value and reference of oldState
remains the same.var1
and var2
are the same, therefore we can say that their values are the same. However, var3
’s value is different since the “semantics” of what it’s holding is different.let var1 = { name: "John", age: 20}
let var2 = { name: "John", age: 20}
let var3 = { name: "May", age: 30}
var1
, is different from the memory address of the object referenced by var2
. In other words, var1
points to a different memory address than var2
. Therefore, their references are different, even though their values are the same!var4
and var5
have the same reference:let var4 = { name: "Jeremy", age: 50}
let var5 = var4
var5.name = “Mary”
, then the value of var4.name
will also be “Mary”.let oldState = {
name: "John",
age: 20,
profession: {
title: "Software Engineer",
organization: "SuperTokens.io"
}
}
let newState = oldState
newState.profession.title = "Senior Software Engineer"
// Shallow comparison. upto level one
if (newState !== oldState || oldState.name !== newState.name || oldState.age !== newState.age || oldState.profession !== newState.profession) {
// Update UI
}
oldState === newState
(if this is false
, then the reference has changed). If the reference has changed, then we can assume that the values must have changed and trigger a render. If not, then we do not rerender.oldState
. Instead, we must always create a new copy of oldState
(in newState
), just like we showed at the start of this article, and make modifications in newState
. Since newState
is a new object, its reference will always be different than that of oldState
. This is known as enforcing immutability of state - exactly what redux enforces its users to do!