0

I have component that I am working on but took it don to the bare minimum to exemplify my issue:

App:

class App extends React.Component{
  render(){
    return(      
      <div className="App"><div style={{width:"500px", height:"300px",margin:"0 auto",marginTop:"100px"}}><PhnGrid/></div></div>
    )
  }
}
export default App;

PhnGrid:

class PhnGrid extends React.Component{
    dataset=[{phonetype:"",phonenumber:""}]
    state = {rowcount:1}
    render(){      
        console.log(this.state)
        return(<h1>HELLO</h1>);
    }
}
export default PhnGrid;

When the PhnGrid component mounts (or when the state changes) render is called twice everytime. Can anyone tell me what going on?

Elcid_91
  • 1,571
  • 4
  • 24
  • 50

1 Answers1

0

Make use of PureComponent instead of Component! PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

class PhnGrid extends React.PureComponent {
    dataset=[{phonetype:"",phonenumber:""}]
    state = {rowcount:1}
    render(){      
        console.log(this.state)
        return(<h1>HELLO</h1>);
    }
}
export default PhnGrid;