카테고리 없음

Why mutation of state doesn't be applied in react

우리로 2023. 12. 16. 12:09

Sometimes mutation of state doesn't change anything.

Because of referential equality

 

React compare two state and if there is change, re render page

At this time react use Object.is() method 

 

Object.is() - JavaScript | MDN

The Object.is() static method determines whether two values are the same value.

developer.mozilla.org

As you can see, Object.is() don't compare 'value'. but the referencial equality!

So even if you declare 'a' as list, assign 'a' to b and update the value, 

Object.is(a,b) return 'true'. so that react doesn't re render page.

 

SO REMEMBER

When updates state in react, always use assign not mutation