Analysis of react hook


Words written in the front

According to the official document of react, hook is a new feature of react 16.8, which allows you to use state and other react features without writing class.

So why do we use hook when we have a class component? Under what circumstances should hook components be used?

React component

React can create components through class and function.

Class component

Analysis of react hook
There are several steps to instantiate a class component

  • Initialization component
  • Execution constructor
  • Inherit parent properties
  • Binding events
  • Initialize state

This will bring some negative effects

  • A large number of component instantiation process will occupy memory, which has a certain impact on performance
  • If the event is bound by bind in the constructor, the readability of the code is poor; and if the event handler is declared by arrow function, it is easy to cause repeated rendering of sub components

Function component

Analysis of react hook
A function component is equivalent to declaring a function that can return UI. The advantage of this is that there is no instantiation process and no burden on memory. Correspondingly, without instantiation, function components have no this, no state, and no access to lifecycle hook functions. Function components are called stateless components.

Function component rendering needs data from the props passed by the parent component

When to declare a component in a functional way?

In the actual project development, the component is not a simple one-tier structure, usually the parent component nesting several child components. We can use class to declare the parent component that needs to use the life cycle processing logic and maintain its own state, and simply use function to declare the child component that receives the parent component props.

React Hook

With the development of “functional programming”, react has developed hook for hook state and life cycle of function components. With hook, the states in components are no longer aggregated into one object, but managed separately; and they no longer need to care about the use of life cycle in development, which gives developers a lot of freedom.

Hook is a special function that allows you to “hook in” react features. For example,useStateIs a hook that allows you to add a state to the react function component


Analysis of react hook
In the figure above, a component called counter is declared by function, and a count state is declared to the component by calling usestate.

What did you do when calling usestate?
It defines a “state variable.”. The variables here are calledcountBut we can call him by any name, for examplebanana. This is a way to save variables when a function is called——useStateIt’s a new method. It’s similar to thethis.stateThe functions provided are exactly the same. Generally speaking, after the function exits, the variable will “disappear”, and the variable in state will be retained by react.

What parameters do usestate need?
useState()The only parameter in the method is the initial state. Different from class, we can assign values to them with numbers or strings as needed, not necessarily objects. In the example, you only need to use numbers to record the number of user clicks, so it’s passed0As the initial state of the variable. (if we want to store two different variables in the state, just calluseState()Two times is enough.)

What does usestate return?
The return values are: current state and function to update state. This is what we writeconst [count, setCount] = useState()The reason for that. It’s not the same as in classthis.state.countandthis.setStateSimilarly, the only difference is that you need to get them in pairs.

After the above operation, we can get count as rendering data in the UI and present it on the view


In the above example, what should we do if we want to print information every time we click the button
Analysis of react hook
Effect hook allows you to perform side effects in function components.

What does useeffect do?
By using this hook, you can tell the react component that it needs to do something after rendering. React will save the function you passed (we call it “effect”) and call it after executing DOM update.

Why call useeffect inside a component?
takeuseEffectPut it inside the component so that we can access it directly in the effectcountState variable (or other props). We don’t need a special API to read it – it’s already in the function scope. Hook uses the closure mechanism of JavaScript instead of introducing a specific react API when JavaScript has provided a solution.

Will useeffect be executed after each rendering?
Yes, by default, it is after the first rendering_ And_ It is executed after each update. You may be more receptive to the idea that an effect occurs “after rendering” without thinking about “mounting” or “updating.”. React ensures that DOM has been updated every time the effect is run.

It can be said that useeffect can replace the life cycle of componentdidmount, componentdidupdate and componentwillunmount in the class component. Every time the component is rendered, the component will perform the operation of useeffect.

Why can useeffect get the value of each update?
After each rendering, the component will generate a new effect, covering the previous value. At this time, the count obtained is also the latest

Parameters passed by useeffect
The first parameter passed in useeffect is a function that represents the operation to be performed by the component after rendering. We can also pass a second parameter in the component – this parameter represents the dependency of useeffect execution. That is to say, only when this parameter changes can useeffect be executed, which realizes the optimization of useeffect

If you want to use this optimization, make sure that the array containsVariables in all external scopes that change over time and are used in the effectOtherwise, your code will refer to the old variables in the previous rendering.

If you want to execute the effect that runs only once (only when the component is mounted and unloaded), you can pass an empty array([])As the second parameter. This tells react that your effect doesn’t depend on any value in props or state, so it never needs to be repeated. This is not a special case – it still follows the way arrays work.

React will delay the execution of useeffect for a period of time after rendering, which makes the extra operation very convenient.

Useeffect return value
Each effect can return a clear function. This brings the logic of adding and removing subscriptions together. They are all part of the effect. It can be thought that the returned function will be executed when the component is unloaded to clean up the timer and other work

When does react know the effect?
React will clear the component when it is unloaded. As you learned before, effects are executed every time you render. This is why react clears the previous effect before executing the current effect.

Why use hook components?

It is difficult to reuse state logic between components

React does not provide a way to “attach” reusable behavior to a component (for example, to connect a component to a store). If you have used react for some time, you may be familiar with some solutions to such problems, such as render props and high-level components. But this kind of solution needs to reorganize your component structure, which may be troublesome and make your code difficult to understand. If you have observed react applications in react devools, you will find that components composed of providers, consumers, high-level components, render props and other abstract layers will form a “nested hell”. This shows a deeper problem: react needs to provide a better native way for shared state logic.

You can use hook to extract state logic from components so that it can be tested and reused separately.Hook enables 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, which are very simple at first, but gradually filled with state logic and side effects. Each life cycle often contains some irrelevant logic. For example, components oftencomponentDidMountandcomponentDidUpdateGet data from. But the samecomponentDidMountIt may also contain many other logic, such as setting up event listening, which needs to be implemented latercomponentWillUnmountClear in. Code that is related and needs to be modified is split, while code that is completely unrelated is combined in the same method. So it is easy to generate bugs and lead to logic inconsistency.

In most cases, it is not possible to split components into smaller granularity because state logic is ubiquitous. This also brings some challenges to the test. At the same time, this is one of the reasons that many people use react with state management library. However, this often introduces a lot of abstract concepts, requiring you to switch back and forth between different files, making reuse more difficult.

To solve this problem,Hook splits the interrelated parts of a component into smaller functions (such as setting subscription or requesting data)Instead of being forced to divide by life cycle. You can also use reducers to manage the internal state of components to make them more predictable.

Embrace functional programming

Hook allows you to use more react features in non class situations.Conceptually, react components have always been more like functions. Hook embraces the function and does not sacrifice the spirit of react. Hook provides solutions to problems without learning complex functional or responsive programming techniques.