[Front-end interview questions] 2023 front-end interview questions - React

There are always ups and downs in a person's life. It will not always rise like the rising sun, nor will it always be miserable. Repeated ups and downs are training for a person. Therefore, those who are floating above do not need to be proud; those who are sinking below do not need to be pessimistic. We must be frank and humble, optimistic and enterprising, and move forward. ——Konosuke Matsushita

Hello everyone, my name is Jiang Chen. In today's Internet environment, everyone must have felt it to some extent. In this impetuous society, only by constantly maintaining one's character can one perceive different gains and encourage each other.

A collection of the latest interview questions in 2023, so be prepared at all times.

This article was first published on WeChat public account: Wild Programmer Jiang Chen

Everyone is welcome to like, collect and follow

Article list

When to use state managers?

From the perspective of the overall structure of the project, it is necessary to choose a speed that suits the project background. If the project background is not suitable for using the status manager, then there is no certain necessity to use it, such as WeChat applet, etc., which can be viewed from the following dimensions

User usage is complex

  • Users with different identities have different usage methods (such as ordinary users and administrators)
  • Collaboration between multiple users is possible
  • Interacting heavily with the server, or using WebSockets
  • View needs to obtain data from multiple sources

From a component perspective

  • The state of a certain component needs to be shared
  • A certain state needs to be available from anywhere
  • A component needs to change global state
  • One component needs to change the state of another component

What is render hijacking?

What is rendering hijacking? The concept of rendering hijacking is the ability to control the output of a component from another component. Of course, this concept is generally explained more clearly together with the higher-order components (HOC) in react.

Higher-order components can do a lot of operations in the render function to control the rendering output of the original component. As long as the rendering of the original component is changed, we call it a kind of rendering hijacking.

In fact, in high-order components, combined rendering and conditional rendering are both types of rendering hijacking. Through reverse inheritance, not only the above two points can be achieved, but also the React elements generated by the render function of the original component can be enhanced.

In actual operations, rendering hijacking can be achieved by operating state and props.

How to achieve internationalization of React components?

The solution that relies on i18next has a very painful problem for huge business projects, and that is the maintenance of json files. Every product iteration needs to add new configurations, so who will maintain this configuration and how to maintain it will cause many problems. And if your project needs to support dozens of languages, what about these dozens of documents? maintain.

Therefore, a more common solution among large manufacturers now is to use AST. Every time a new version is developed, all codes are scanned through AST to find out the Chinese in the code. Chinese is used as the key and the intelligent translation service is called to automatically generate the project. json file. In this way, humans no longer need to maintain json files, everything relies on tools for automation. At present, there are already open sources from major manufacturers, such as Didi’s di18n and Alibaba’s kiwi.

How does React do code splitting? What is the principle of splitting?

I think the prerequisite for react splitting is code directory design specifications, module definition specifications, code design specifications, and compliance with general principles of program design, such as high cohesion, low coupling, etc.

In our react project:

  • At the api level, we encapsulate it separately and expose the results of http requests to the outside world.
  • In the data layer, we use mobx encapsulation to handle asynchronous requests and business logic processing.
  • In the view layer, try to use the data passed from the mobx layer to modify the logic.
  • Static type resources are placed separately
  • Public components, high-order components, and plug-ins are placed separately
  • Tool files are placed separately

Where to catch errors in React?

Official website example:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你同样可以将错误日志上报给服务器
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

use

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

But error bounds won't catch:

try{}catch(err){}
///异步代码(例如 setTimeout 或 requestAnimationFrame 回调函数)
///服务端渲染
///它自身抛出来的错误(并非它的子组件)

Why are props in React read-only?

The design pattern that ensures react's one-way data flow makes the state more predictable. If self-component modification is allowed, then a parent component will pass the state to several sub-components. If these sub-components are modified at will, it will be completely unpredictable. We don’t know where the state is modified, so we must protect props from being modified like pure functions. Revise

How to use Hooks to obtain server-side data?

import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
  const [data, setData] = useState({ hits: [] });
  useEffect(async () => {
    const result = await axios(
      'https://api/url/to/data',
    );
    setData(result.data);
  });
  return (
    <ul>
      {data.hits.map(item => (
        <li key={item.objectID}>
          <a href={item.url}>{item.title}</a>
        </li>
      ))}
    </ul>
  );
}
export default App;

What principles should be followed when using Hooks?

  1. Only use Hooks at the top level

Don't call Hooks inside loops, conditionals or nested functions, make sure to always call them at the top level of your React function.

  1. Only call Hooks in React functions

Don't call Hooks in ordinary JavaScript functions. you can:

  • ✅ Call Hook in React function component
  • ✅ Call other Hooks in custom Hooks

What problem is React Fiber designed to solve?

Due to the recursion uninterruptible problem of the React15 StackReconcilersolution, if the Diff time is too long (JS calculation time), it will cause the page UI to become unresponsive (such as input boxes) and vdomcannot be applied to domit.

In order to solve this problem, React16 implemented a new requestIdleCallbackscheduler based on (due to requestIdleCallbackcompatibility and stability issues, I implemented it myself polyfill). Through the idea of ​​task priority, when a high-priority task enters, it interrupts reconciler.

In order to adapt to this new scheduler, it was launched FiberReconcilerto convert the original tree structure (vdom) into the form of Fiber linked list (child/sibling/return). The entire Fiber traversal is based on loops rather than recursion and can be interrupted at any time. .

More importantly, the Fiber-based linked list structure has a very good application foundation for subsequent (React 17 lane architecture) asynchronous rendering and (possible) worker calculations.

Tell me what you think are the best practices in React

Refer to the official website

Why does React need Hooks?

Official website answer:

motivation

Hooks solve a variety of seemingly unrelated problems we've encountered over five years of writing and maintaining thousands of components. Whether you are learning React, use it every day, or would rather try another framework with a similar component model to React, you may be familiar with these issues.

Reusing state logic between components is difficult

React does not provide a way to "attach" reusable behavior to components (for example, connecting components to a store). If you've been using React for a while, you might be familiar with some solutions to this problem, such as render props and higher-order components. But such solutions require reorganizing your component structure, which can be cumbersome and make your code difficult to understand. If you observe React applications in React DevTools, you will find that components composed of providers, consumers, higher-order components, render props and other abstraction layers will form a "nested hell". Although we can filter them out in DevTools, this illustrates a deeper problem: React needs to provide a better native way for shared state logic.

You can use Hooks to extract state logic from components so that the logic can be tested independently and reused. Hooks allow you to reuse state logic without modifying the component structure. This makes it easier to share Hooks between components or within the community.

Complex components become difficult to understand

We often maintain some components. The components are simple at first, but gradually become filled with state logic and side effects. Each life cycle often contains some unrelated logic. For example, components often obtain data in componentDidMount and componentDidUpdate. However, the same componentDidMount may also contain a lot of other logic, such as setting up event listening, which then needs to be cleared in componentWillUnmount. Code that is related and needs to be modified is split up, while completely unrelated code is combined in the same method. This can easily lead to bugs and logical inconsistencies.

In most cases, it is not possible to split components into smaller granularities because stateful logic is everywhere. This also brings certain challenges to testing. At the same time, this is one of the reasons why many people use React with a state management library. However, this often introduces a lot of abstract concepts and requires you to switch back and forth between different files, making reuse more difficult.

To solve this problem, Hooks split the interrelated parts of the component into smaller functions (such as setting up a subscription or requesting data), rather than forcing them to be divided according to the life cycle. You can also use reducers to manage a component's internal state to make it more predictable.

Incomprehensible class

In addition to the difficulties encountered in code reuse and code management, we also found that classes are a major barrier to learning React. You have to understand how this works in JavaScript, which is very different from other languages. Don't forget to bind event handlers. There is no stable syntax proposal and the code is very redundant. Everyone can understand props, state and top-down data flow very well, but they are at a loss for classes. Even among experienced React developers, there are disagreements about the differences between function components and class components, and even the usage scenarios of the two components.

Also, React has been out for five years, and we hope it will keep up with the times in the next five years as well. As libraries like Svelte, Angular, Glimmer, and others have shown, component precompilation has huge potential. Especially when it's not limited to templates. Recently, we have been using Prepack to experiment with component folding and have achieved initial results. However, we found that using class components inadvertently encouraged developers to use solutions that invalidated optimization measures. classes also pose some problems to current tools. For example, classes don't compress well and can make hot reloading unstable. Therefore, we wanted to provide an API that makes the code easier to optimize.

To solve these problems, Hooks allow you to use more React features without classes. Conceptually, React components have always been more like functions. Hooks embrace functions without sacrificing the spiritual principles of React. Hooks provide solutions to problems without having to learn complex functional or reactive programming techniques

What problem does state management solve?

Focus on the view layer

This is the introduction to React’s official website. JavaScript library for building user interfaces. The characteristics of focusing on the view layer determine that it is not an all-round framework. Compared with all-round frameworks such as Angular, React has simpler and single functions. For example, there is no front-end routing, no state management, no one-stop development documentation, etc.

f(state) = view

The react component renders the page based on state (or props), similar to a function that inputs state and outputs view. However, this is not MDV (Model Driven View) in the complete sense and does not have a complete model layer. By the way, I feel that componentization and MDV are currently popular in front-end development, and it is the general trend...

state flows from top to bottom, Props are read-only

We have understood this feature since we first started writing React. The flow direction of state is from the outside to the inside of the component, and from top to bottom, and the props passed are read-only. If you want to change the props, you can only pass a packaged setState method from the upper component. Unlike angular, which has ng-model, vue has v-model, which provides two-way binding instructions. This is the convention in React. You may think it is cumbersome, but the flow of state is clearer. One-way data flow is always more pleasing in large spas.

These characteristics determine that React itself does not provide powerful state management functions. There are roughly three native methods.

Do functional components have a life cycle?

It does not provide the concept of life cycle, unlike class components that inherit React.component, which allows you to use life cycle and specifically emphasize related concepts.

What is the principle of immutable?

Use dictionary tree to persist data structure, optimize object generation logic and reduce costs when updating

How to prevent HTML from being escaped?

dangerouslySetInnerHTML

Tell me how you improve the rendering efficiency of components

render

what is

React is based on the perfect combination of virtual DOM and efficient Diff algorithm to achieve the smallest granularity update of DOM. In most cases, React's rendering efficiency of DOM is sufficient for our daily business.

In complex business scenarios, performance problems will still trouble us. At this time, some measures need to be taken to improve running performance. Avoiding unnecessary rendering is one of the common optimization methods in business.

How to do

Class component:
  • InheritPureComponent
  • Optimize using shouldComponentUpdate
Function component:
  • memo simulates PureComponent
  • Use useMemo to cache variables
  • Use useCallback cache function
  • Add keys in a loop. It is best to use the unique value of the array item for key. Index is not recommended.

Summarize

In the actual development process, front-end performance issues are an issue that must be considered. As the business becomes more complex, the probability of encountering performance problems also increases.

In addition, it is recommended to granulate the page into smaller granularities. If one is too large, when the state is modified, it will cause the rendering of the entire large component. After the components are split, the granularity becomes smaller, and the Ability to reduce unnecessary rendering of subcomponents

Talk about your understanding of high-order components (HOC)?

Higher-order function, a function that meets at least one of the following conditions

  • Accepts one or more functions as input
  • output a function

In React, a higher-order component accepts one or more components as parameters and returns a component. It is essentially a function, not a component.

const EnhancedComponent = highOrderComponent(WrappedComponent);

In the above code, the function accepts a component WrappedComponentas a parameter and returns the processed new component.EnhancedComponent

This implementation of higher-order components is essentially a decorator design pattern.

Tell me about your understanding of React refs?

Refs are called Resilient File System in computers (English: Resilient File System, referred to as ReFS)

Refs in React provide a way to access DOM nodes or React elements created in the render method

It is essentially the component instance returned by ReactDOM.render(). If it is a rendering component, it returns the component instance. If it renders dom, it returns the specific dom node.

class

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref="myref" />;
  }
}

hooks

function App(props) {
  const myref = useRef()
  return (
    <>
      <div ref={myref}></div>
    </>
  )
}

Guess you like

Origin blog.csdn.net/weixin_42439919/article/details/133065905