Om Agrawal
Om Agrawal

Reputation: 21

React Re-Render and update issue

  1. Suppose I have 10k of record and whenever I am trying to update state using setState every time component is re-render but I want after all changes on state component should render once only. example :-
constructor(){
     this.state={
        employeeList:[{name:a},{name:b},{name:c},{name:d},{name:e}.....]
     }
 }

I want to update a,b,c,d,e to 1 ,2 ,3 ,4,5 by using this.setState() but after update all value i need to re-render component not after update one by one.

Please help me.

Upvotes: 1

Views: 870

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281646

You need to handle your state updates differently

Instead of updating state separately for each value, you would update it once like

update() {
   const newValues = [1,2,3,4,5];
   const newEmployeeList = this.state.employeeList.map((obj, index) => {
      return {...obj, name: newValues[index]};
   })
   this.setState({employeeList: newEmployeeList})
}

Upvotes: 0

Yossi
Yossi

Reputation: 6027

There are two possible ways to do this:

  • Use the 'shouldComponentUpdate' and decide in it whether to render.
  • Use a pure component.

Using 'shouldComponentUpdate'

The following text is copied from "How does React decide to re-render a component?":

"By default, shouldComponentUpdate returns true. That’s what causes a component to render everytime there is a state change. However, you can overwrite shouldComponentUpdate to give it more “smarts” if you need the performance boost. Instead of letting React re-render all the time, you can tell React when you don’t want to trigger a re-render."

Use a pure component

The following text is copied from "Why and How to Use PureComponent in React.js": "PureComponent changes the life-cycle method shouldComponentUpdate and adds some logic to automatically check whether a re-render is required for the component. This allows a PureComponent to call method render only if it detects changes in state or props."

Upvotes: 1

Related Questions