For ordinary class components, they are full-featured, but complex. For example, constructor, lifecycle, etc. Sometimes we just need the render method, so there are function components.

Class components: powerful, multifaceted, cumbersome.

Function components: relatively weak (before hooks), few things, convenient.

Where is the weak function of function components? (Before hooks)

1. No state. Changes in state can cause your rerendering to group.

2, this. This in a class component points to the component instance by default. Function components do not have this. Because of strict mode, the default point is undefined. Class components must bind this when passing functions to their children.

3. Reference (ref).

4. Life cycle.

Second, the class component deficiencies

1. It is difficult to reuse state logic between components. Before hooks came along, if we wanted to reuse the state of a component. The first way is to use props. The second type is higher-order components. In this way, nesting problems can occur. Hooks allow you to reuse state logic without modifying the component structure.

2. Complex component logic becomes increasingly complex to the point of incomprehension. When maintaining some components, they may start out simple, but become more and more complex over time. We might write more and more complex logic in componentDidMount and componentDidUpdate, and some event listening, and need to touch listening in componentWillUnmount. Hooks can be used to break the interrelated parts of a component into smaller functions.

To use the React class component, you need to be familiar with the JS classes, such as this in class. Hook uses more functions and reduces the learning cost.

The advantages of Hooks

Reusing state logic without modifying component structure (custom Hooks) Reusing state logic without modifying component structure (custom Hooks) Reusing state logic without modifying component structure (custom Hooks) Reusing state logic without modifying component structure (custom Hooks) Reusing state logic without modifying component structure Side effects refer to logic that does not occur during the data-to-view transformation, such as Ajax requests, accessing native DOM elements, local persistent caching, binding/unbinding events, adding subscriptions, setting timers, logging, and so on. In the past, these side effects were written in the class component lifecycle functions. UseEffect is executed after the rendering is complete, useLayoutEffect is executed after the browser layout and before the painting

Fourth, the Hooks

1, useState(defaultValue) =>

Once useState is executed, the value is not changed immediately, but the next time it is rendered. Unlike setState, useState replaces rather than merges values. If the new state is computed from the old state, you can pass a method to setState, taking the previous state as the first argument, just as a class component’s setState passes a function. Lazy initialization state: If the initial value of useState needs to be computed, you can pass useState a function that will only be called during initial rendering. In React hooks, use object.is () to determine whether state is equal to state.

UseReducer ((state, action) => newState)

UseRducer is very simple to use, similar to Redux. UseReducer can be more useful than useState in some situations, such as when the state logic is complex and contains multiple subvalues, or when the next state depends on the previous state.

3, useContext (context)

Receive a context object (the return value of React. CreateContext) and return the current value of the context. The current value of the context is the value of < myContext.provider > from the upper component closest to the current component Prop decides that this Hook will trigger a rerender when the most recent <MyContext.Provider> update is made to the upper layer of the component. UseContext (MyContext) is equivalent to static contextType = MyContext or useContext(MyContext) < myContext.consumer > useContext(MyContext) just lets you read the value of the context and subscribe to changes in the context. You still need to use < myContext. Provider> in the upper component tree to provide context for the lower component

4, useEffect

Effect: Logic that does not occur during the data-to-view transformation, such as Ajax requests, accessing native DOM elements, local persistent caching, binding/unbinding events, adding subscriptions, setting timers, logging, etc. Changing the DOM, sending Ajax requests, and performing other side effects inside function components (in this case, during the React rendering phase) were previously not allowed, as they could cause unexplained bugs and break UI consistency.

UseEffect adds the ability to manipulate side effects to function components. You can simulate componentDidMount, componentDidUpdate, and componentWillUnmount in the class component. UseEffect receives a function that is not executed until the component has been rendered to the screen. This function can return a function that clears side effects, which are executed before the component is unloaded to prevent memory leaks. If the component is rendered multiple times, the previous effect is cleared before the next effect is executed. Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser update screen, making your application seem more responsive. In most cases, effects do not need to be executed synchronously. In rare cases (such as measuring layout), there is a separate useLayoutEffect Hook (synchronization, which blocks updates) available for you to use, with the same API as useEffect. UseEffect if the second parameter is not taken into account, it is executed every time you re-render. Each time you re-render, a new effect is generated, replacing the previous one. In a sense, an effect is more like a part of a render result — each effect belongs to a specific render. Skip Effect for performance optimization: useEffect the second argument, the dependency array, controls the execution of useEffect. If you want to execute effect only once (only when the component is mounted and unmounted), you can pass an empty array ([]) as the second argument. This tells React that your effect doesn’t depend on any value in props or state, so it never needs to be repeated. It is recommended that useEffect be passed as second parameter as possible. Separation of concerns is achieved using multiple effects

UseRef, forwardRef, useImperativeHandle

The forwardRef can forward the ref object from the parent to the DOM element in the child because the function component doesn’t have an instance. UseImperativeHandle lets you customize the ref instance exposed to the parent component. The first argument is passed to the component’s second REF object retrieved from the parent element. The second argument is the custom Ref instance

6, useCallback (fn, deps)

A function that returns to the cache and rewrites it only when an item in the DEPS changes. If dePS is not passed in, each component rendering is recalculated.

7, useMemo(() => fn, deps)

Returns cached variables, which are rewritten only when items in dePS change. If dePS is not passed in, each component rendering is recalculated. UseCallback (fn, deps) equivalent to useMemo(() => fn, deps)

5. Custom Hook

Custom hooks are more of a convention than a feature. If the function name starts with use and calls other hooks, it is called a custom Hook

Sometimes we want to reuse some state logic between components, either using render props, higher-order components, or redux

Six, need to pay attention to the problem

Hooks can only be used in function components.

2. Hooks must be used at the top level of the component.

3. Custom hook can only start with use.

4. UseEffect is used for functions that rely on props or state or data derived from it.

5, do not rely too much on useMemo, useCallback, they have their own overhead, use useMemo need to consider three questions: is the function passed to useMemo expensive? Some calculations are expensive, so we need to “remember” the return value to avoid recalculating every render. If the operation you are performing is not expensive, there is no need to remember the return value. Otherwise, the cost of using useMemo itself may exceed the cost of recalculating the value. Therefore, for some simple JS operations, we do not need useMemo to “remember” its return value. Is the value returned original? If the values calculated are primitive then every comparison is equal and the components used are not re-rendered; If a value of a complex type is computed, even if the value remains the same, the address will change, causing the used component to be re-rendered. So we also need to “remember” this value. When writing custom hooks, the return value must be consistent with the reference. Because you can’t be sure how the external is going to use its return value. Bugs can occur if the return value is used as a dependency on other hooks and the references are inconsistent every time re-render (when the value is equal). So if the values exposed in a custom Hook are Object, array, function, etc., useMemo should be used. To ensure that references do not change when the values are the same. UseEffect cannot accept async as a callback function. UseEffect accepts functions that either return a function that clears side effects, or that return no value. Async returns a Promise.