TransWikia.com

Does changing state cause re-render in ReactJS

Stack Overflow Asked by CodeRocks on November 12, 2021

In my ReactJS application, I have an array of dictionaries stored as a state called items that looks like this:

this.state = {
   items: []
}

I then add items to the list after certain events, ex: click a button, which causes this.state.items to continue to grow to look like something like this:

items: [{"item": "milk", "price": 3.00}, {"item": "eggs", "price": 5.00}]

The items state directly influences my UI because

this.state.items.map((item, i) => <><h1>{item.item}</h1><p>{item.price}</p></>)

My question is: Is this causing my UI to have to re-render items in the items list that have already been renders every time the items state changes. If so, how do I fix that?

Thank you!

One Answer

That depends on how you set the state, if you use the provided this.setState then yes, react will notice and re-render your app. If you instead do state = { /* some new state */ } then it might not re-render. I hope this answers your question.

Please next time just check the React docs (State and Lifecycle)

Answered by DownloadPizza on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP