InterviewSolution
| 1. |
Explain the new feature of React Memo in React v16.6? |
|
Answer» The new feature of React Memo are used to solve the problem which we get if the state is not updating in this.setState, but STILL all components are re-rendered. To solve this problem we use two solutions. One is to CHECK and COMPARE state in shouldComponentUpdate and if they are same, we don’t re-render components. The other solution is to use PureComponents. See question 51for details. But both of them can’t be used with functional components. Let’s look at the problem again. Here we have a FunctionalComp, which gets the same state passed every 3 sec. import React, { Component } from "react"; import FunctionalComp from "./components/functionalComp"; import "./App.css"; class App extends Component { state = { val: 1 }; componentDidMount() { setInterval(() => { this.setState({ val: 1 }); }, 3000); } render() { RETURN ( <div className="App"> <header className="App-header"> <FunctionalComp val={this.state.val} /> </header> </div> ); } } export default App;The FunctionalComp is below. import React from “react"; export default (props) => { console.log("val =", props.val); return <div>{props.val}</div>; };So, if we run it we get a value of 1 every 3 seconds printed like below. We can solve it by wrapping the component in React.memo. import React from “react"; export default React.memo(props => { console.log("val =", props.val); return <div>{props.val}</div>; });Now the output is just one 1 and after that, as every time the state of it is set to one, so no more RENDERS. |
|