Abstract: React Hooks principle resolution.
- Original: a quick overview of the principles React Hooks
- Translator: Front Ash
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 PureComponent
optimized 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.memo
functions.
React 16.8 new out Hook
lets React function components with status and provides similar componentDidMount
and componentDidUpdate
so on life-cycle approach.
Classes are will replace it?
Hooks
Does 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. Hooks
It 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 sayHi
method.
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 implementrender
and 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
.
useState
It 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.setState
a state to change the entire target.
Component no state function, but the useState
hook 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 Hook
creation of these states in a particular way, and did not like components in the function setState
to change the state function, so Hook needs a function to update each state. So the useState
return 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 useWhatever
and 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 React
can 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 React
calling them at the appropriate time, the returned object structure thereof React
can be converted to DOM
the 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 hook
time, 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 useState
three times, React will hook into these three Hooks array when the first rendering.
The next time rendering, the same 3
one hooks
invoked in the same order, so React
you can view it in the array, and the position has been found 0
to have a useState
hook, it React
does 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:
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
nextHook
property, it was put index0
position, the first hook operation will occupy the position0
.React to call your component (which means that it knows to store
hooks
metadata objects).- Calls
useState
, React create a new state, put ithooks
on an array of0
bits, and returns the[volume,setVolume]
pair andvolume
set to its initial value80
, it will alsonextHook
index incremented by one. - Called again
useState
, React view of the array of1
bits, saw it was empty, and create a new state. It will thennextHook
index is incremented2
, and returns[position,setPosition]
. The third call
useState
. React to see the position2
is empty, it is also creating a new state, thenextHook
increment to3
, and return[isPlaying,setPlaying]
.
Now, hooks
the array has 3
a hook, rendering is complete. What will happen next time rendering?
React
It requires re-rendering components, as has been seen this before React component, which has been associated metadata.React
ThenextHook
index is reset0
, and the calling component.- Calls
useState
, React to view the index0
hooks at the array and found it already has a hook in the groove. There is no need to re-create one, it willnextHook
advance to the index1
and return[volume,setVolume]
, whichvolume
is still set80
. - Called again
useState
. This time,nextHook
as1
soReact
indexed array is checked1
. Similarly, hook already exists, so it incrementsnextHook
and returns[position,setPosition]
. - 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 AudioPlayer
the 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 hooks
calling customizations hooks
may be hooks
combined. 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 !