An overview of the React

know

  • The MVC framework;
  • Browser side/server side can run;
  • ReactDom.render()Convert a template toHTMLRender and insert the specified DOM;
  • JSX grammar;
  • It is divided into component class (stateful component) and function component (stateless component).

Stateful and stateless components

  • Stateful components: inherited from the Component class; You can use state and props, and you can use this to call this.state and this.props; There are life cycle functions;

  • Stateless component: is a function; Only props can be used, and this is not required; No life cycle;

JSX

  • Basic syntax rules: in case of < start with HTML syntax parsing, in case of {with JS rules parsing;

  • Allows variables to be inserted directly into templates, wrapped in {}. If the variable is an array, all members of the array are expanded;

  • Component properties can be obtained from the this.props object. The properties of the object correspond to the properties of the component. But the class attribute needs to be className instead;

    for

    The attribute should be htmlFor because class and for are reserved words for JS; In addition, this.props. Children represents all of the children of the component and has three possible values: This is undefined if the component has no children, object if it has one child, and array if it has multiple children, so be careful when handling this.props. Children. React provides a tool method to handle this.props. Children;

  • Children: you can use React.Children. Map to traverse child nodes without having to worry about the stateful component.

  • PropTypes: Component class attributes;

  • Get the real DOM node: Because the stateful component this.refs.[refName] property gets the real DOM, you must wait until the virtual DOM is inserted into the document before using this property, otherwise an error will be reported.

Life cycle (stateful component)

  • Three life cycles:Mounting.Updating.Unmounting; Two handlers are provided per lifecyclewillCalled before entering the state,didCalled after entering the state;
  • Seven event handlers:ComponentsWillMount (), componentsDidMount(), componentsWillUpdate (), componentsWillUnmount(); In addition, there arecomponentWillReceiveProps()When the loaded component receives a new parameter,shouldComponentUpdate()Called when determining whether a component needs to be rerendered;

Important: The React function component and its hooks

Functional components (stateless components)

Idea: Write components as pure functions as possible, and use hook functions if additional functionality and hooks are needed.

Functions are components; Capitalize the first letter; Do one thing, return HTML code without any side effects; Each time a component is rendered, the function component is automatically executed.

hook

Hooks are functions; Function component side effect solution; Introduce side effects for function components; Specific side effects require specific hooks, such as useState(state hook), useContext(shared state hook), useReducer(state management hook), useRef(reference hook), etc. UseEffect is a generic side effect.

UseEffect: Side effect hook

React framework provided internally; Function component internal call; Component rendering is performed each time a function component is called;

  • Parameters: two parameters, the first parameter is the side effect function, the second parameter is the array. The second argument uses an array to specify the dependencies of the side-effect function, which are re-executed only if the dependencies change. When an empty array is used, meaning that no dependencies are attached, only the first page rendering is performed.

    UseEffect (() => {// Want to execute the side effect}, []);

  • Usage scenarios: get data, listen to events or subscribe, modify DOM, output logs, etc

  • Return value: Allows a function to be returned, executed when the component is unloaded/re-executed, that can be used to remove added side effects.

  • Note: For multiple unrelated side effects, multiple USE effects should be called, not mixed together.

UseState: status hook

React framework provided internally; Function component internal call; Generate a state variable to hold data. Normally each call to set automatically triggers the render function to rerender the component, but multiple sets in a useEffect call only trigger the function component to rerender once.

  • Parameter: accepts the initial value of the state as the parameter;
  • Return value: This function returns an array whose first member is a variable pointing to the current value of the state. The second member is a function that updates the status with the conventionsetPrefixes the variable name of the state;

UseRef: Reference hook

  • Properties that remain constant across render cycles, that is, after a component has been rendered multiple times, apply to variables that remain constant over multiple renders;

  • Can reflect previous state

    let param = useRef(‘default value’); param.current = ‘new value’; console.log(‘param’, param.current);

  • Modifying it will not cause the component to render;

  • Can be used to get components or DOM nodes;

    let ele = useRef(); console.log(‘ele’, ele.current);

    / / the react in the template

UseContext: Shared state hook

  • State is shared between multiple components
  • usage.useContextwithcreateContextCombined use;
  • A change in the state value triggers a re-rendering

UseReducer: state management hook

  • React does not provide state management. Instead, use external libraries such as Redux.

  • The core concept of Redux is that components emit actions to communicate with the state manager. After the state manager receives the action, the Reducer function is used to calculate the newState. The Reducer function is in the form (state, action) => newState. The useReducers() hook is used to introduce the Reducer function.

  • usage

  • Because Hooks can provide shared state and Reducer functions, it can replace Redux in these areas. However, it doesn’t provide middleware or time travel, so if you need those, use Redux.

useCallback

  • The component is executed when it is first rendered and then when the function it depends on changes
  • Reflect current Status
  • Caching mechanism for performance tuning
  • Application scenario: Rely on local state or props to create situations where functions need to be cached to avoid unnecessary updates

useMemo

  • The component is executed when it is first rendered and then when its dependent variables change
  • Reflect current Status
  • Caching mechanism for performance tuning
  • Application scenario: Avoid unnecessary updates

Encapsulate your own hooks

  • Use theusePrefix naming;

Difficulty: How to choose and use hooks reasonably

useState or useReducer

useMemo or useCallback

React.memo() or redux

Routing module: react-router-dom

  • useHistory

    const history = useHistory();

Status management module: React-redux

  • useDispatch

    const dispatch = useDispatch();

The DEMO address:

Github.com/CYLpursuit/…

Resources: www.ruanyifeng.com/blog/2016/0…

www.ruanyifeng.com/blog/2020/0…

www.ruanyifeng.com/blog/2019/0…

zhuanlan.zhihu.com/p/63385235