preface

Recently, due to the company’s project development, I learned the use of Hook in React and had a basic understanding of it and how to apply hook in the project. This blog is mainly introduced from the following points:

How to implement the declaration cycle function hook in the class component

Firstly, I will introduce the meaning of hook and some scenes it needs to face

React 16.8 Hook is a new feature. It lets you use state and other React features without having to write a class. React features can be used with function components: It is difficult to reuse the state logic between components. Hook can solve the problem that you need to reuse the state logic without modifying the previous component structure. In the case of not using Hook, some advanced usages such as advanced component, provider and customer need to be used. May is the difficulty in understanding For complex components can be to spin off its logic, such as when you use life cycle function, different life cycles shall be carried out at different times, so at this time for complex components, there is a lot of logic in some life cycle function, on the readability is compromised. When hook is used, component logic can be divided and the same logic can be integrated together, which greatly increases readability and facilitates maintenance without the need to understand the class component. When you first learn, you have to understand the meaning of this keyword in the current component. This is not required in hooks. The react feature can be used only when the class component is not used. The following part is how to use the hook and class components

state hook

This. State = {} is the most common way to use global variables in class components, but in hook we use useState hook. You can then refer to the global variable by its name.

Const [count, setCount] = useState(0) const [count, setCount] = useState(0) const [count, setCount] = useState(0) Const [count, setCount] = useState({}), so that when you use count, you get an empty object. Returns a state and a function that updates the state function: The new state needs to be computed by using the previous state, passing a function to setState, which will receive the previous state and return an updated lazy initialState. The initialState parameter will only be used in the initial rendering of the component. If the initialization state needs to be obtained by a complex calculation, you can pass in a function that computes and returns the initial state, which is only dropped during the initial render, as follows:

How to set values for global variables in hook

SetState (); setState(); setState(); setState(); setState()

What we’ve seen here is that count can get the value, so the corresponding setCount(value), which is the way to assign a value to the count variable, and then count can get the value.

Why take this approach? React’s one-way data source ensures that your data source flow is clearer. This is how React differs from Vue’s two-way data source binding hook in setting multiple global variables

In a hook, if we need to set more than one count, we need to use the useState hook several times. Of course, you can also set a variable outside the hook, that is, outside the hook function component. Don’t need to be aware of is in the whole hook global Settings in this function, so in the operating mechanism of hook, at every time of loading, will go to the inside of the load from the new variables, so you won’t be able to get within the entire function in the use value of the variable changes, to be able to get just the initial value of the variable *

useEffect hook

UseEffect Hook is similar to a lifecycle function in a class component to handle things that need to be done at a certain point in time, often referred to as side effects. When using useEffect hook, it should not be included in a loop or statement, otherwise the project will report an error. This is also a hook setting mechanism

Do not need to clear: Run some extra code after React DOM update: send network request, manually change DOM, log, etc. When using the useEffect hook, it is important to pay attention to the timing of its rendering. By default, it is executed on the first rendering and every update. How to control this rendering timing is explained in detail in the following section: Tell the component why useEffect is called inside the component after rendering: The effect variable in state can be accessed directly in effect: Effect Optional cleanup mechanism. Each effect can return a cleanup function that receives: a function that contains an imperative and may have side effects. The function passed to useEffect is delayed after the browser has finished laying out and drawing, so it should not be used to update the browser screen. Default condition execution: it is executed after each round of component rendering is complete, so effect will be recreated whenever its dependencies change. To change its timing, you need to pass a second parameter to useEffect, and the subscription will be recreated only if the value of the second parameter changes. If you want to use this optimized approach, you need to make sure that the array contains all variables that will change in the external scope and are used in effect. If you want to run Effect only once, you can pass an empty array as the second argument. To get a preliminary understanding of useEffect, you only need to know the above. Here is an example from the official website to illustrate useEffect

UseEffect is a hook. “You clicked ${count} times” on the clicked page every time the count changes.

UseEffect the way in which lifecycle functions in calSS are replaced

The phases of a stateful component’s lifecycle function in React

In the Mounting phase constructor() static getDerivedStateFromProps() render() componentDidMount() 2.updating

static getDerivedStateFormProps shouldComponentUpdate() render() getSnapshotBeforeUpdate() componentDidUpdate() 3. UnMouting

ComponentWillUnmount () uses hooks instead of life cycle functions

Constructor: Initialize State componentDidMount() using useState instead of hook by passing the second argument to useEffect, which is an empty array and will only be executed once, as shown below

UseEffect (() => {}) {componentDidUpdate();}

UseEffect (() => {},[count]) useEffect(() => {},[count])

ComponentWillUnmount () requires a callback, as shown below

ShouldComponentUpdata (), often used as a react.Memo, is used by default to make shallow comparisons to complex objects in the props object. If you want to control the comparison, provide a custom comparison function as the second argument. The way to replace hook is as follows

Customize the hook

This kind of custom hook is usually necessary in actual project development, if the hook is used throughout the project. Usually, it is to use the hook defined by useState and useEffect. When you call it, you can directly call the hook defined by you to achieve the function you need. The following takes the user-defined useReducer hook as an example

In the above practical example, we have encapsulated a custom useReducerhook, which can be called to complete the same functions as reducer. In the call, we need to pass in two parameters, one is reducer and the other is initialState. And then you get the state, and then you get the Dispatch method. Note that the return value is an array. The advantage of this is that we can use an array structure to retrieve the return value. For details on the structure of arrays, see the section in ES6. The next step is to use this custom useReducer. Use as follows

The actual usage is not written down here, the rest can be filled in, and it is used in the same way as redux. This is the whole custom hook and the process to use, in the actual development can go to experience. Additional hooks

UseReducer can optimize the performance of components that will start deep updates. It can send dispatch to sub-components rather than call back the encapsulation of the useReducer hook.

  1. Lazy initialization of useReducer, optionally to create an initialization state lazy. Therefore, we need to set an initialization function passed in as the third parameter of the useReducer, so that the initialization state will be set to init(initialArg), as shown below, which is a practical case of passing the third parameter in the useReducer

  2. Note: If the reducer hook returns the same value as the current state, React skips the rendering of the child components and the execution of the side effects

UseCallback Return value: Returns a Memoized callback function that is updated only when a dependency changes. Meaning: Pass the inline callback function and its array of dependencies as arguments to the useCallback, It will return the callback data to the optimized and use reference equality to avoid unnecessarily rendering useCallBack(fn, deps) equivalent to useMemo(() => fn,deps) useMemo Const memoziedValue = useMemo(() => computeExpensiveValue(a,b), [a, b]) Return an Memoized value that is passed to useMemo as parameters to create a function and an array of dependencies. Memoized values are recalculated only if a dependency changes. Benefits: This optimization helps avoid costly computational rendering every time you render: functions passed into useMemo are executed during rendering, and do not perform non-rendering operations inside this function, such as side effects that are part of useEffect. If not, the new value will be rerendered each time. Note: The dependency array is not passed to the function as an argument. In summary, every parameter that appears in a function should also appear in the dependency array. const refContainer = useref(initialValue); Return value: Returns a refable object whose.current property is initialized as the parameter passed in. The difference between ref and useRef is that the latter creates a normal JS object, useRef, and creates a {current:… . The only difference with the} object is that useRef returns the same ref useImperativeHandle on each rendering: you can customize the instance value exposed to the assigned component when using ref, using the following form:

UseLayoutEffect update timing: Execute before the browser performs the next draw. Like useEffect, effect useDebugValue is called synchronously after all DOM changes: React devTools is often used as a display tag, as a performance optimization in client-side hook hooks

If, for some reason, a function cannot be moved inside effect, try the following way to move the function outside the current component. If the game method called is a pure calculation, etc., If you want to add a function dependency, explicitly use a hook outside of useCallback, as shown in the following example

shouldComponentUpdate

As shown above, this implementation does not use hooks, it is equivalent to pure components, but only props can be compared. You can add a second parameter and use a function to get the old and new props. If the result returns true, you can skip the update phase and remember the calculation result using the useMemo hook to cache the calculation between multiple renderings

The above code calls computeExpensiveValue(a,b), but their dependencies on a, B are unchanged, so useMemo returns the value of the last result directly

For learning about the hooks as mentioned above, is to hook the content also many so to hook the study had better be to go to the website to see, link the following react.docschina.org/docs/hooks-…

Baby naming – a naming consultant who knows more about young parents