2022 essential react interview questions with answers
React Video Explanation Click to learn
1. How to use the strict mode of react and what is its use?
StrictMode is a tool used to highlight potential problems in applications. Like Fragment, StrictMode does not render any visible UI. It triggers additional checks and warnings for its descendant elements. Strict mode can be enabled for any part of the application. For example:
import React from 'react'; function ExampleApplication() { return ( <div> <Header /> <React.StrictMode> <div> <ComponentOne /> <ComponentTwo /> </div> </React.StrictMode> <Footer /> </div> ); } Copy code
In the example above, a strict mode check is not run on the Header and Footer components. However, ComponentOne and ComponentTwo and all their descendant elements will be checked.
StrictMode currently helps:
- Identify unsafe life cycles
- Warning about using obsolete string ref API
- Warning about using the obsolete findDOMNode method
- Detect unexpected side effects
- Obsolete context API detected
2. What are the traversal methods in React?
(1) Traversal array: Map & & foreach
import React from 'react'; class App extends React.Component { render() { let arr = ['a', 'b', 'c', 'd']; return ( <ul> { arr.map((item, index) => { return <li key={index}>{item}</li> }) } </ul> ) } } class App extends React.Component { render() { let arr = ['a', 'b', 'c', 'd']; return ( <ul> { arr.forEach((item, index) => { return <li key={index}>{item}</li> }) } </ul> ) } } Copy code
(2) Traversal object: Map & & for in
class App extends React.Component { render() { let obj = { a: 1, b: 2, c: 3 } return ( <ul> { (() => { let domArr = []; for(const key in obj) { if(obj.hasOwnProperty(key)) { const value = obj[key] domArr.push(<li key={key}>{value}</li>) } } return domArr; })() } </ul> ) } } // Object.entries() converts an object into an array class App extends React.Component { render() { let obj = { a: 1, b: 2, c: 3 } return ( <ul> { Object.entries(obj).map(([key, value], index) => { // Item is an array. Deconstruct item in [key, value] return <li key={key}>{value}</li> }) } </ul> ) } }
3. How to retain data when a page is reloaded in React?
Data persistence is designed for this problem. The main implementation methods are as follows:
- Redux: store the data of the page in Redux, and obtain the data in Redux when reloading the page;
- Data.js: for a project built with webpack, you can create a file, data.js, save the data in data.js, jump to the page and get it;
- sessionStorge: before entering the address selection page, when componentWillUnMount, store the data in sessionStorage. Each time you enter the page, judge whether there is a stored value in sessionStorage. If so, read the rendering data; If not, the data is initialized. Return to or enter the page other than the selected address, clear the stored sessionStorage, and ensure that the next entry is initialized data
- History API: the pushState function of the history API can associate an arbitrary serializable state with the history, so you can save some information of the current page in the state when routing the push. The next time you return to this page, you can take the data before leaving from the state and re render it. React router can be directly supported. This method is suitable for some scenarios that need temporary storage.
4. Must react use JSX?
React does not force the use of JSX. When you do not want to configure JSX compilation in the build environment, it is more convenient not to use JSX in react.
Each JSX element just calls the syntax of react. CreateElement (component, props,... Children). Therefore, anything you can do with JSX can be done with pure JavaScript.
For example, code written in JSX:
class Hello extends React.Component { render() { return <div>Hello {this.props.toWhat}</div>; } } ReactDOM.render( <Hello toWhat="World" />, document.getElementById('root') ); Copy code
You can write code that does not use JSX:
class Hello extends React.Component { render() { return React.createElement('div', null, `Hello ${this.props.toWhat}`); } } ReactDOM.render( React.createElement(Hello, {toWhat: 'World'}, null), document.getElementById('root') );
5. Why is it necessary to introduce react instead of react in jsx components?
In essence, JSX is the syntax sugar of the react. CreateElement (component, props,... Children) method. Before React 17, if JSX is used, it is actually using react. babel will convert the component into createElement. After React 17, we no longer need to introduce it, because babel can help us automatically introduce react.
5. How to use async/await in React?
async/await is a new feature in the ES7 standard. If it is a project created using the official scaffold of React, it can be used directly. If it is used in a webpack configuration project built by yourself, you may encounter an abnormal error of regeneratorRuntime is not defined. Then we need to introduce babel and configure async/await in babel. You can use babel's transform async to module method plug-in to convert it into the syntax supported by the browser. Although there is no performance improvement, it has a better coding experience.
6. What is the difference between react.children.map and js map?
The map in JavaScript will not process null or undefined data, while the map in React.Children.map can handle null or undefined data.
7. What design patterns are used for high-order components in react?
Decoration mode is used, and the application of high-order components:
function withWindowWidth(BaseComponent) { class DerivedClass extends React.Component { state = { windowWidth: window.innerWidth, } onResize = () => { this.setState({ windowWidth: window.innerWidth, }) } componentDidMount() { window.addEventListener('resize', this.onResize) } componentWillUnmount() { window.removeEventListener('resize', this.onResize); } render() { return <BaseComponent {...this.props} {...this.state}/> } } return DerivedClass; } const MyComponent = (props) => { return <div>Window width is: {props.windowWidth}</div> }; export default withWindowWidth(MyComponent); Copy code
The feature of decoration mode is that it does not need to change the decorated object itself, but only sets a shell interface on the outside. At present, JavaScript has a proposal for a native decorator. Its usage is as follows:
@testable class MyTestableClass { }
8. What are the differences between class components and function components?
answer
Before React version 16.8 (introduction of hooks), class based components were used to create components that need to maintain internal state or utilize life cycle methods (i.e. componentDidMount and shouldComponentUpdate). The class based Component is the ES6 class, which extends the Component class of React and implements at least the render() method.
Class components:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } Copy code
The function component is stateless (again, less than react version 16.8) and returns the output to render. Their preference for rendering the UI depends only on properties because they are simpler and more powerful than class based components.
Function component:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } Copy code
Note: the introduction of hooks in React 16.8 means that these differences no longer apply (see questions 14 and 15).
Further reading
- Compare functional components and class components in React
- Comparison of function and class components in React
9. What is the role of keys in react?
Keys is an auxiliary identifier used by React to track which elements in the list have been modified, added or removed.
When rendering a collection in React, adding keywords to each repeating element is very important to help React track the association between elements and data. key should be a unique ID, preferably UUID or other unique string in the collection item:
<ul> {todos.map((todo) => <li key={todo.id}> {todo.text} </li> )}; </ul> Copy code
When adding and deleting items in a collection, not using keys or using a cable reference as a key can lead to strange behavior.
Further reading
10. Why call setState instead of changing state directly?
answer
If you try to change the state of a component directly, React will not know that it needs to re render the component. By using the setState() method, React can update the UI of the component.
In addition, you can talk about how to ensure that status updates are not synchronized. If you need to update the state of a component based on another state (or property), pass a function to setState(), which takes state and props as its two parameters:
this.setState((state, props) => ({ counter: state.counter + props.increment })); Copy code
Further reading