1

I'm looking for the best approach where I can compare my current values in the state/props with the new values in state/props while using shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState)

Let's consider an example if I have following data in my state

[
        {
          title: "Hello",
          id: 1,
          isUpdated: false,
          property: [
            {
              name: "property 1",
              area: "area 1",
              inspection: [
                {
                  isNew: true,
                  isSold: false,
                  isLicenseExpired: false
                }
              ]
            },
            {
              name: "property 2",
              area: "area 2",
              inspection: [
                {
                  isNew: false,
                  isSold: false,
                  isLicenseExpired: true
                }
              ]
            }
          ]
        },
        {
          title: "World",
          id: 2,
          isUpdated: false,
          property: [
            {
              name: "property 1",
              area: "area 1",
              inspection: [
                {
                  isNew: false,
                  isSold: false,
                  isLicenseExpired: true
                }
              ]
            },
            {
              name: "property 2",
              area: "area 2",
              inspection: [
                {
                  isNew: false,
                  isSold: false,
                  isLicenseExpired: true
                }
              ]
            }
          ]
        }
      ]

Now when I update the state again with the same data I cannot compare it manually with prev and current props/state because if I compare it like nextProps.data !== this.props.data it will give my wrong result as it only does the shallow comparison.

I also know that I can use lodash library to deep compare the values, but I wanted to know the best way of comparing the nested array of the object in shouldComponentUpdate()

Here is the live example - https://codesandbox.io/s/crazy-perlman-f3e1k?fontsize=14 In case you are interested to see my code and problem.

Thanks for your time.

Harsh Makadia
  • 3,263
  • 5
  • 30
  • 42

1 Answers1

1

This thread has a perhaps too extensive answer for your question. JSON.stringify is one way to go, but slow. Lodash, underscore also work. Or you can use one of the functions the responders in the thread have provided.

How to compare arrays in JavaScript?

Craig Gehring
  • 3,067
  • 1
  • 9
  • 11