Search code examples
reactjsreact-lifecycle

Why the componentDidUpdate is infinitely updated?


I need to drop a picture, then upload it to the server and update the interface. I have a problem, the lifecycle method componentDidUpdate is beginning to be updated infinitely, in the condition I indicated to compare this.state with the prevState. (PrevState is undefined, I can not understand why).

I put my code in the sandbox, I hope it will be clear. https://codesandbox.io/s/headless-smoke-4xxi2


Solution

  • WHY: This seems like a reference/variable memory address issue.

    When you are storing to itemsList you are creating a new reference because you are receiving a non-primitive value from the api. JS always operates with references when it comes to non-primitive values. So, your if (this.state.itemsList !== prevState.itemsList) will always return true because itemsList is an array which is non-primitive data set which means JS is not checking it's values but only the references.

    I see two solutions atm in this case:

    1. Prevent updating the state if the values are same

    OR

    1. Check by values with appropriate checker function in this statement if (this.state.itemsList !== prevState.itemsList)

    Hope I was able to explain. Cheers!