As we learned in our previous article that variables are reactive in nature. It means they update the UI with changes in their values. But this statement is half correct. Let me rephrase it with the correct version – “variable assignment is reactive in nature”. It means the UI will only re-render when a new value is assigned to the variable.
So, all the operations where a manipulation in the value happens without assignment, there UI re-rendering doesn’t happen. For example, if you have an array and you are pushing a new value to it then it’s not an assignment and hence there won’t be a call for re-rendering.
Here are the few operations which prevents re-rendering – push()
, pop()
, shift()
, unshift()
, splice()
etc. So, you need to check in your code if you are using any of these functions. This code won’t re-renders –
var someArr = [1, 2, 3, 4] function pushValue(val){ someArr.push(val) } function popValue(){ someArr.pop() } function unshiftValue(val){ someArr.unshift(val) } function shiftValue(){ someArr.shift() }
Note: If UI is not updating then it doesn’t mean that variable value isn’t changed. It already did but just not reflected on UI reactively. Also, object key assignment or array value assignment will work absolutely fine. This will be reactive –
var someObj = {a: 1, b: 2} var someArr = [1, 2] someObj.a = 3 someArr[0] = 3
Solution
The solution to this problem is Assignment. But how to replace the above array functions with assignments? There are multiple ways and one of them is using spread operator (...
).
Spread operator is used to create a copy of an array. So, if I write –
var firstArray = [1, 2, 3, 4] var copyArray = [...firstArray]
then copyArray
will have the same values as firstArray
but both of them will be exclusive. If we simply assign like this –
var copyArray = firstArray
then, both copyArray
and firstArray
will refer to the same array and making changes in any of them will be reflected in other too.
We can use spread operator to mimic the functionality of array functions. Like this –
var arrayVariable = [1, 2, 3, 4] function pushValue(val){ arrayVariable.push(val) arrayVariable = [...arrayVariable] } function popValue(){ arrayVariable.pop(); arrayVariable = [...arrayVariable] } function shiftValue(){ arrayVariable.shift() arrayVariable = [...arrayVariable] } function unshiftValue(val){ arrayVariable.unshift(val); arrayVariable = [...arrayVariable] }