React Hooks what exactly is it?

Abstract: React Hooks principle resolution.

Most of us can save the state React class components, and components can not function? And the class has a life cycle of components, and components can not function?

React earlier version, class components can inherit PureComponentoptimized rendering unnecessary, assembly with respect to the function, not the official website React provide a corresponding method for caching function to reduce unnecessary components rendering, 16.6 out of the direct React.memofunctions.

React 16.8 new out Hooklets React function components with status and provides similar componentDidMountand componentDidUpdateso on life-cycle approach.

Classes are will replace it?

HooksDoes not replace the class, they are just a new tool that you can use. React team said they have no plans to abandon the class React, so if you want to continue using them, you can continue to use.

I can understand that there is always a feeling of new things to learn, however painful, I will not feel the same as we always backward. HooksIt can be used as a nice new features to use. Of course, there is no need to use Hook to reconstruct the original code, React team also is not recommended.

Go Go

Take a look at Hooks example, let's start with the most familiar start: function components.

The following is a function of the components OneTimeButton things done is when we click on the call sayHimethod.

    import React from 'react';
    import { render } from 'react-dom';
    
    function OneTimeButton(props) {
      return (
        <button onClick={props.onClick}>
            点我点我
        </button>
      )
    }
    
    function sayHi() {
      console.log('yo')
    }
    
    render(
      <OneTimeButton onClick={sayHi}/>,
      document.querySelector('#root')
    )

We want this component to do is track whether it is clicked, if clicked, the button is disabled, just as a one-time switch.

But it requires a State, because it is a function, it is impossible to have a state (before React 16.8), it is necessary to re-class configuration.

Function to convert components, class components during about five stages:

  • Deny: Maybe it does not need to be a class, we can state put elsewhere.
  • Implementation: Nonsense, you must turn it into a class, is not it?
  • Acceptance: All right, I'll change.
  • Overtime efforts to rewrite: First write class Thing extends React.Component, then implement renderand so on.
  • Finally: Adding state.

    class OneTimeButton extends React.Component {
      state = {
        clicked: false
      }
    
      handleClick = () => {
        this.props.onClick();
    
        // Ok, no more clicking.
        this.setState({ clicked: true });
      }
    
      render() {
        return (
          <button
            onClick={this.handleClick}
            disabled={this.state.clicked}
          >
            You Can Only Click Me Once
          </button>
        );
      }
    }

This is a fair amount of code, structural components has undergone great changes, we need a number of small features, you need to rewrite a lot.

Use Hook easily add State

Next, use the new useState hook function is added to the general state of the components:

    import React, { useState } from 'react'
    
    function OneTimeButton(props) {
      const [clicked, setClicked] = useState(false)
      
      function doClick() {
        props.onClick();
        setClicked(true)
      }
    
      return (
        <button
          onClick={clicked ? undefined : doClick}
          disabled={clicked}
        >
          点我点我
        </button>
      )
    }

How this code works

Most of this code looks like an ordinary function assembly to write us a minute ago, in addition useState.

useStateIt is a hook. Its name to "use" the beginning of (this is Hooks rule one - their names have to "use" the beginning).

useState hook state parameter is the initial value, and returns an array of two elements: current state and a state function for change.

Class state component has a large target, a function of this.setStatea state to change the entire target.

Component no state function, but the useStatehook allows us to add a small state block when needed. So, if you only need a Boolean value that we can create some of the state to save it.

Since the Hookcreation of these states in a particular way, and did not like components in the function setStateto change the state function, so Hook needs a function to update each state. So the useStatereturn is a pair of corresponding relations: a value, a function of the value of the update. Of course, the value can be anything - any type JS - Number, Boolean, objects, arrays, and so on.

Now, you should have a lot of questions, such as:

  • When a component is re-rendered, will not be re-created each time a new state do? How to React to know what the old state?
  • Why hook name must "use" the beginning? This looks very suspicious.
  • If this is a naming convention, does that mean I can customize Hook.
  • How to store more complex state, many scenes is not just only a state worth so simple.

Hooks magic

The status information is stored in the function component seemingly stateless, this is a strange paradox. This is the first question on the hook, we must figure out how they work.

The first guess is that the original author was behind the operation of the public some of the compiler. Search code useWhateverand in a manner to replace it with a logic state.

Then I heard the call to order of the rules (they each have to call in the same order), it makes me even more confused. That's how it works.

React When first rendering function components, it will also create an object coexist, the object is an object of the custom component instance, not the global object. As long as the components present in the DOM, the component of the object will always exist.

Using this object Reactcan be tracked bits belonging to various metadata component.

Remember, React component even function components have never been self-rendering. They do not directly return HTML. Component depends on Reactcalling them at the appropriate time, the returned object structure thereof Reactcan be converted to DOMthe node.

React has the ability to do some settings before calling each component for which it is set the state of the time.

Which do one thing setting Hooks array. It is initially empty, each call a hooktime, React will be added to the array hook.

Why order is important

Let's assume this has the following components:

    function AudioPlayer() {
      const [volume, setVolume] = useState(80);
      const [position, setPosition] = useState(0);
      const [isPlaying, setPlaying] = useState(false);
    
      .....
    }

Because it calls useStatethree times, React will hook into these three Hooks array when the first rendering.

The next time rendering, the same 3one hooksinvoked in the same order, so Reactyou can view it in the array, and the position has been found 0to have a useStatehook, it Reactdoes not create a new state, but returns existing state.

That React to create and maintain state in multiple function calls in a way that each time the variable itself goes out of scope.

More useState call example

Let's look in more detail how this is achieved, the first rendering:

  1. React When creating a component, it does not call the function. React to create metadata objects and Hooks empty array. Assuming that this object has a named nextHookproperty, it was put index 0position, the first hook operation will occupy the position 0.

  2. React to call your component (which means that it knows to store hooksmetadata objects).

  3. Calls useState, React create a new state, put it hookson an array of 0bits, and returns the [volume,setVolume]pair and volumeset to its initial value 80, it will also nextHookindex incremented by one.
  4. Called again useState, React view of the array of 1bits, saw it was empty, and create a new state. It will then nextHookindex is incremented 2, and returns [position,setPosition].
  5. The third call useState. React to see the position 2is empty, it is also creating a new state, the nextHookincrement to 3, and return [isPlaying,setPlaying].

Now, hooksthe array has 3a hook, rendering is complete. What will happen next time rendering?

  1. ReactIt requires re-rendering components, as has been seen this before React component, which has been associated metadata.
  2. ReactThe nextHookindex is reset 0, and the calling component.
  3. Calls useState, React to view the index 0hooks at the array and found it already has a hook in the groove. There is no need to re-create one, it will nextHookadvance to the index 1and return [volume,setVolume], which volumeis still set 80.
  4. Called again useState. This time, nextHookas 1so Reactindexed array is checked 1. Similarly, hook already exists, so it increments nextHookand returns [position,setPosition].
  5. The third call useState, I think you know what happened.

That's it, know the principles, it looks not so magical, but it does rely on some rules, so only use Hooks rules.

Hooks rules

Custom hooks function only need to comply with Rule 3: Their names must "use" as a prefix.

For example, we can from AudioPlayerthe extraction assembly to the three states in the own custom hooks:

    function AudioPlayer() {
      // Extract these 3 pieces of state:
      const [volume, setVolume] = useState(80);
      const [position, setPosition] = useState(0);
      const [isPlaying, setPlaying] = useState(false);
    
      // < beautiful audio player goes here >
    }

Therefore, we can create a new function to deal specifically with these states, and use some additional method returns an object to make it easier to start and stop playback, such as:

    function usePlayerState(lengthOfClip) {
      const [volume, setVolume] = useState(80);
      const [position, setPosition] = useState(0);
      const [isPlaying, setPlaying] = useState(false);
    
      const stop = () => {
        setPlaying(false);
        setPosition(0);
      }
    
      const start = () => {
        setPlaying(true);
      }
    
      return {
        volume,
        position,
        isPlaying,
        setVolume,
        setPosition,
        start,
        stop
      };
    }

One benefit is that a state such as this may be extracted together and associated logic behavior. Can extract a set of states and event handlers, and other related update logic, which can not only clean up the assembly code, you can also make these reusable logic and behavior.

Further, in the custom hookscalling customizations hooksmay be hookscombined. hooks just function, of course, the function can call other functions.

to sum up

Hooks provides a new way to deal with the problem React, where the idea is very interesting and novel.

React team integrates a set of great documentation and a Frequently Asked Questions , from the need to rewrite all the class components to create the function because the hook Hooks whether in the rendering slow down? And everything in between, so be sure I want to see.

After the code is deployed may exist BUG can not know in real time, and afterwards in order to solve these BUG, we spent a lot of time debugging log, here for everyone to recommend a way BUG easy to use monitoring tools Fundebug .

Original: https://daveceddia.com/intro-to-hooks/

About Fundebug

Fundebug focus on JavaScript, applets micro-channel, micro-channel games, Alipay small program, React Native, Node.js and Java applications in real-time online monitoring BUG. Since 2016 double eleven formally launched, Fundebug handled a total of 2 billion + error event, paying customers have Sunshine Insurance, walnut programming, lychee FM, head of the 1-to-1, micro pulse, the Youth League and many other community brands. Welcome to Free Trial !

Guess you like

Origin www.cnblogs.com/fundebug/p/what-is-react-hooks.html