InterviewSolution
| 1. |
What are Pure components in React |
|
Answer» React.PureComponent is one of the most significant ways to optimize React applications that is easy and fast to implement. The usage of React.PureComponent gives a considerable increase in performance because it reduces the number of render operation in the application. By default, a plain React.Component has shouldComponentUpdate set to always return true. A common pitfall when converting from Component to PureComponent is to forget that the children need to re-render too. As with all React - if the parent doesn’t re-render the children won’t either. So if you have a PureComponent with children, those children can only update if the parent’s state or props are shallowly DIFFERENT (causing the parent to re-render). This is how React shallow compares (copied from React source code) Code sample below In the given example when we extend Display component from React.Component the render function will be called each time you click the button. Instead if you extend the Display component from React.PureComponent the render function will be called only once. That means it CALLS render when the prop Is shallowly different import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; import Display from "./Display"; function App() { return ( <div className="App"> <Display chek={10} /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);import React from "react"; CLASS Display extends React.PureComponent { CONSTRUCTOR(props){ super(props); this.state = { obj1: 1 } } updateMe = () => { this.setState({ obj1: this.props.chek }); }; render(){ console.log("render called"); return ( <> <div>{this.state.obj1}</div> <div> <button type="submit" onClick={this.updateMe}> click here </button> </div> </> ) } } export default Display;import React from "react"; class Display extends React.Component { constructor(props){ super(props); this.state = { obj1: 1 } } updateMe = () => { this.setState({ obj1: this.props.chek }); }; render(){ console.log("render called"); return ( <> <div>{this.state.obj1}</div> <div> <button type="submit" onClick={this.updateMe}> click here </button> </div> </> ) } } export default Display; |
|