After writing react for 3 months, what have I learned?

Time:2021-12-19

After writing react for 3 months, what have I learned?

Original link:
React those things
React hooks

The new environment is transferred from Vue to react technology stack, which is an interesting process.

In react, you will see many similarities and differences with Vue. You encounter some doubts in the learning process and make records.

  • How does useref solve the null pointer problem?
  • What is the difference between useeffect and usecallback (usememo)?
  • In addition to transmitting data through props, how can react transmit data through context?
  • React. React. In createElement (input, props) How to understand createElement?
  • What is FC in react?FC<[interface]>What do you mean? What are the main uses and abbreviations?
  • What are props, context, proptypes, contexttypes, defaultprops and displayName of FC formal parameters in react?
  • import { MouseEvent } from 'react'What do you mean? What is the type of synthetic event?
  • React.forwardRefWhat do you mean? What does useimperativehandle mean?

How does useref solve the null pointer problem?

In general, useref is used to reference the DOM node of the component. Ref in Vue refers to a Vue component. Unlike Vue, ref in react not only refers to DOM nodes, but also generates an object reference with unchanged memory.

Example of null pointer caused by usestate

const [foo, setFoo] = useState(null);

const handler = () => {
    setFoo("hello")
}

useEffect(() => {
    return () => {
      //In any case, foo is null, and adding foo to DEPs of useeffect is not enough
      if (foo === "hello") {
          // do something...
      }
    }
}, [])

Correct example of using useref (solving the problem of null object in event handler)

const foo = useRef(null)

const handler = () => {
    foo.current = "hello"
}

useEffect(() => {

    return () => {
      // foo. Current is hello
      if (foo.current === "hello") {
          // do something...
      }
    }
}, [])

What is the reason why useref solves the null pointer problem?

  • During the component life cycle, the objects pointed to by useref always exist
  • Each time you render, useref points to the same referenced object

To sum up:The memory address of the objects generated by useref remains unchanged during the component life cycle.

const refContainer = useRef(initialValue);

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: …} object yourself is that useRef will give you the same ref object on every render.

To sum up, we will use useref to solve the null pointer problem:

  • Event handler
  • setTimeout,setInterval

What is the difference between useeffect and usecallback (usememo)?

Browser execution phase:Visible modification (DOM operation, animation, transition) – > style rule calculation – > calculate space and position – > Draw pixel content – > multiple layer synthesis
The first four phases are for elements, and the last one is for layers. From point to surface.
After writing react for 3 months, what have I learned?

Different execution times

Useeffect executes the function after rendering, more accurately after layout and paint are completed.

The function passed to useEffect will run after the render is committed to the screen.Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint

Usecallback (usememo) executes functions during rendering.

Remember that the function passed to useMemo runs during rendering.

Which are suitable for execution after rendering and which are suitable for execution during rendering

After rendering, execute: mutations (DOM operation), subscriptions (subscription), timers, logging
Execute during rendering: used for performance optimization that does not depend on the completion of rendering. It is executed as soon as the state changes

An example illustrates the difference between useeffect and usememo

The main problems solved by usememo:How to control some functions not to be triggered when DOM changes.
For example, in the following example, when the name changes, useeffect will start the price function after DOM rendering, and usememo can accurately trigger only the function that updates the name.

This is a very, very good example. A more detailed blog post is here: what is the difference between usememo and useeffect? How to use usememo

import React, {Fragment} from 'react'
import { useState, useEffect, useCallback, useMemo } from 'react'

const nameList = ['apple', 'peer', 'banana', 'lemon']
const Example = (props) => {
    const [price, setPrice] = useState(0)
    const [name, setName] = useState('apple')
    
    
    function getProductName() {
        console. Log ('getproductname trigger ')
        return name
    }
    //Respond only to name
    useEffect(() => {
        console. Log ('name effect triggered ')
        getProductName()
    }, [name])
    
    //Respond only to price
    useEffect(() => {
        console. Log ('price effect triggered ')
    }, [price])
  
    //Memoized getproductname function
    const memo_getProductName = useMemo(() => {
        console. Log ('name memo trigger ')
        Return() = > name // returns a function
    }, [name])

    return (
        <Fragment>
            <p>{name}</p>
            <p>{price}</p>
            <p>Normal name: {getproductname()}</p>
            <p>Memoized: {memo_getproductname()}</p>
            < button onclick = {() = > setprice (price + 1)} > price + 1 < / button >
            < button onclick = {() = > setname (namelist [math. Random() * namelist. Length < < 0])} > modify the name < / button >
        </Fragment>
    )
}
export default Example

Click the price + 1 button (through usememo, redundant memo_getproductname() is not triggered, but only price related functions are triggered)

Getproductname trigger
Price effect trigger

Click the modify name button (only the name related is triggered through useeffect)

Name memo trigger
Getproductname trigger
Name effect trigger
Getproductname trigger

summary

When useeffect is faced with DOM rendering that depends on a state, there will be some performance problems, and usememo can optimize this problem.
Finally, use one sentence to summarize the words of usememo, that is:Usememo can avoid unnecessary repeated rendering and execution problems that can not be determined by useeffect.

In addition to transmitting data through props, how can react transmit data through context?

Assuming that the component level is deep, props needs to be passed down level by level, which can be said to be a props shell problem.
Components encapsulated in context provide a way for components that need to accept dataTransfer across component levels and import parent props as neededThe way.

Component definition context part

import * as React from 'react'
// myContext.ts
interface IContext {
     foo: string,
     bar?: number,
     baz: string
}
const myContext = React.createContext<IContext>({
     foo: "a",
     baz: "b"
})


interface IProps {
    data: IContext ,
}

const myProvider: React.FC<IProps> = (props) => {
     const {data, children} = props
     return <myContext.Provider value={data}>{children}</myContext.Provider>
}

export default myProvider;

export function useMyContext() {
  return useContext(myContext)
}

Using components and context sections

<!--  Component package -- >
import myProvider from './myContext.ts'

<myProvider data={{foo: "foo", baz: "baz"}}>
    <div className="root">
        <div className="parent">
            <Component1 />
            <Component2 />
        </div>
     </div>
</myProvider>
// Component1
import  {useMyContext} from './myContext.ts'
const {foo, baz} = useMyContext()

const Compoonent1 = () => {
    return (<div>{foo}{baz}</div>)
}
export Component1

React. React. In createElement (input, props) How to understand createElement?

React.createElement()

React.createElement(
    type,
    [props],
    [...children]
)

Returns a new react element according to the specified type.

Type this parameter can be:

  • A “tag name string” (e.g. “div”, “span”)
  • A react component type (a class or a function)
  • A react fragment type

Components written in JSX will eventually be resolved to react Createelement(). If you use JSX, you do not need to explicitly call react createElement()。

React.createElement(Input, props)

The method of encapsulating general form components based on antd.

// generator.js
import React from "react";
import { Input, Select } from "antd";

const components = {
  input: Input,
  select: Select
};

export default function generateComponent(type, props) {
  return React.createElement(components[type], props);
}

Simply use this common form component method:

import generateComponent from './generator'

const inputComponent = generateComponent('input', props)
const selectComponent = generateComponent('select', props)

You may think the above method is weak, but it is very useful if you generate components in batch.

// components.js
import React from "react";
import generateComponent from "./generator";

const componentsInfos = [
  {
    type: "input",
    disabled: true,
    defaultValue: "foo"
  },
  {
    type: "select",
    autoClear: true,
    dropdownStyle: { color: "red" }
  }
];

export default class Components extends React.Component {
  render() {
    return componentsInfos.map((item) => {
      const { type, ...props } = item;
      return <>{generateComponent(type, props)}</>;
    });
  }
}

For specific examples: https://codesandbox.io/s/reac…

Based on this method, reusable business components can be encapsulated: form business components, form business components, etc., which will greatly liberate productivity!

What is FC in react?FC<[interface]>What do you mean? What are the main uses and abbreviations?

What is FC in react?

type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

FC is the abbreviation of functional component, which is a generic interface.

FC<[interface]>What do you mean?

Is to provide a functional component environment for wrapping components.
Why? Because hooks can be used inside functional components.

Functional component

const Component = (props) => {
    //You can use hooks here
    return <div />
}
perhaps
function Component(props) {
  //You can use hooks here
  return <div />;
}

What are the main uses and abbreviations?

The common functional component within the project is used as a component container to provide hooks context.

// Container.js
import React, { FC } from 'react'

interface IProps {
     children: any
}

const Container: FC<IProps> = (props) =>  {
  return (
    <div>
      {props.children}
    </div>
  )
}

export default Container
//Use
<Container>
    <Component1 />
    <Component2 />
</Container>

What are props, context, proptypes, contexttypes, defaultprops and displayName of FC formal parameters in react?

type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
        (props: PropsWithChildren<P>, context?: any): ReactElement | null;
        propTypes?: WeakValidationMap<P>;
        contextTypes?: ValidationMap<any>;
        defaultProps?: Partial<P>;
        displayName?: string;
}

type PropsWithChildren<P> = P & { children?: ReactNode };

Props and context are formal parameters of function components.
Proptypes, contexttypes, defaultprops and displayName are the functions and properties of the component.

const Foo: FC<{}> = (props, context) => {
    return (
        <div>{props.children}</div>
    )
}
Foo.propTypes = ...
Foo.contextTypes = ...
Foo.defaultProps = ...
Foo.displayName = ...

What is the difference between react functional components and pure functional components?

1. React functional components must return reactelement or null, and the return value of pure functional components is not limited
2. The props of react functional components limit the type of children to reactnode, while pure functional components do not
3. React functional components have type constraints such as proptypes, contexttypes, defaultprops, displayName, etc. pure functional components are not limited

https://stackoverflow.com/que…

import { MouseEvent } from 'react'What do you mean? What is the type of synthetic event?

import { MouseEvent } from 'react'What do you mean?

Good article: https://fettblog.eu/typescrip…

  • Constraints for event types
  • In addition to mouseevent, there are animationevent, changeevent, clipboard event, compositionevent, dragevent, focusevent, formevent, keyboardevent, mouseevent, pointerevent, touchevent, transitionevent, wheelevent As well as SyntheticEvent
  • have access toMouseEvent<HTMLButtonElement>Constraints only trigger events for HTML button dom
  • Inputevent is special because it is an experimental event, so it can be replaced by synthetic event

What is the type of synthetic event?

Synthetic – > synthetic

In react, almost all events inherit the interface of synthetic event.
Synthetic event is a cross browser browser event wrapper, which is usually used to replace event types such as inputevent.

interface SyntheticEvent<T = Element, E = Event> extends BaseSyntheticEvent<E, EventTarget & T, EventTarget> {}
interface BaseSyntheticEvent<E = object, C = any, T = any> {
    nativeEvent: E;
    currentTarget: C;
    target: T;
    bubbles: boolean;
    cancelable: boolean;
    defaultPrevented: boolean;
    eventPhase: number;
    isTrusted: boolean;
    preventDefault(): void;
    isDefaultPrevented(): boolean;
    stopPropagation(): void;
    isPropagationStopped(): boolean;
    persist(): void;
    timeStamp: number;
    type: string;
}

React. What does forwardref mean? What does useimperativehandle mean?

In short, refs forwarding is to get the DOM node inside the component.
React. Forwardref meansRefs forwardingIt is mainly used to automatically transfer refs to a sub component through components, which is common in reusable component libraries.

When using forwardref, some components can receive refs and pass them down to sub components, or “forward” to sub components.

There are no components that use refs forwarding.

function FancyButton(props) {
  return (
    <button className="FancyButton">
      {props.children}
    </button>
  );
}

Components forwarded using refs.

const FancyButton = React.forwardRef((props, ref)=>{
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
})

How to use?

//Create a ref variable
const ref = React.createRef();
//Pass the ref variable into fancybutton, which forwards the ref variable to button
<FancyButton ref={ref}></FancyButton>
//Ref.current points to the button DOM node

There are also different refs mechanisms in Vue, but if Vue wants to obtain the DOM nodes inside the sub components, it needs to obtain them level by level, such asthis.$refs.parent.$refs.child, this can lead to heavy component level dependencies.
Compared with Vue, the refs forwarding component level of react is lighter, and the code readability and maintainability are higher.

What does useimperativehandle mean?

import React, { useRef, useImperativeHandle } from 'react';
import ReactDOM from 'react-dom';

const FancyInput = React.forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    publicFocus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} type="text" />
});

const App = props => {
  const fancyInputRef = useRef();

  return (
    <div>
      <FancyInput ref={fancyInputRef} />
      <button
        onClick={() => fancyInputRef.current.publicFocus()}
      >The parent component calls the focus < / button > of the child component
    </div>
  )
}

ReactDOM.render(<App />, root);

In the above example, unlike direct forwarding ref, direct forwarding ref is to forward react The ref parameter on the function in forwardref is directly applied to the ref attribute of the return element. In fact, the parent and child components refer to the current object of the same Ref. it is officially not recommended to use such ref transparent transmission. After using useimperativehandle, the parent and child components can have their own refs respectively through react Forwardref transparently passes the ref of the parent component, and defines the current opened to the parent component through the useimperativehandle method.

We look forward to communicating with you and making common progress:

  • WeChat official account: large front-end / excellent_ developers
  • GitHub blog: 233 personal blogs while you are still young
  • Segment fault column: be an excellent front-end engineer while you are still young

Strive to be an excellent front-end engineer!

Recommended Today

Tool | how to perform TPC-C test on MySQL?

Author: Ding Yuan, radondb test director Responsible for the quality performance test and iterative verification of radondb cloud database and container database. Have in-depth research on cloud database and container database performance and high availability solutions. background According to the report on the significance of China’s self-developed database reaching the top of TPC-C [1] released […]