By default, the reader of this article already knows something about React Hooks. The React Hooks API Reference is a Reference to the react-hooks API
The React Hooks basis
Use React Hooks to refer to the React function component.
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
A component is like a JavaScript function that takes props and returns the React element.
When we first learned to use the React framework, we first learned to write components through the Class. This allows us to understand and plan the data and methods of the Class components, and the life cycle allows us to have a clearer understanding of the loading of components and the triggering of state updates.
What about function components? The function component itself handles the mapping from data to React elements, and Hooks provide data storage and Side effects handling on top of that.
For the moment, let’s forget what we know about classes and lifecycles and relearn React from the function component + Hooks.
0. Function components
The function component is used to process some simple UI components, and encapsulates some components abstractly by passing data to the Props.
function Header(props) {
const { title, description, avatar } = props;
return (
<div>
<img src={avatar} />
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}
Copy the code
One of the reasons for limiting the use of functional components is that they have no internal data and, on the other hand, no life cycle, so they cannot achieve some interactive and logical functions.
1. Data stores when using React Hooks
Variables defined in a function component are not fixed and are cleaned up after execution (non-closure). So, we need to fix some data for the component using Hooks.
Edit on CodeSandbox
Use useState from React Hooks. Use useState from React Hooks.
With useState, we define an object somewhere and mount it somewhere where it won’t disappear. The first value returned by the useState method is the data we want. The second value returned by the useState method is a function that sets the value of this object and then triggers the function to rerender.
The above mess is very vague about what a place is, what kind of object it defines, and where it’s mounted. How do you trigger rendering after setting new values?
Github source link
Before understanding Hook loading, it is necessary to understand the definition and storage of Hook.
Here is the Hook type definition
export type Hook = {
/ / data
memoizedState: any.// The following is not needed for the moment
baseState: any,
baseQueue: Update<any.any> | null,
queue: UpdateQueue<any.any> | null.// The pointer to the next node in the list
next: Hook | null};Copy the code
What we need to understand is that hooks are stored through linked lists
- The first time a function component executes
The first Hook will be mounted to the React Fiber Node, and subsequent hooks encountered during function execution will be mounted to the Hook nodes in sequence.
- Function component updates when rendered
Function execution encounters Hooks that sequentially read the Hooks on the React Fiber Node.
As shown above, function components rely on the order of the Hooks queue when executing again. Using a Hook in a conditional judgment would mess up the queue.
Therefore, there will be the following official website tips:
Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
2. Use React Hooks to handle side effects
Side effects, as I understand them, are special occasions that occur during the data -> view transformation process. We can use these opportunities to work on some business logic.
Here is a simple counting Demo using useEffect.
Edit on CodeSandbox
UseEffect to do something that needs to be done after rendering is complete. React useEffect can also be found in the React useEffect API Reference.
We can further understand useEffect Hook through flow chart.
Here is the useEffectHook execution logic. Through this diagram, you can see that useEffect is an additional step in the process of data alignment. SideEffect is invoked only if the following conditions are true.
- UseEffect Is executed for the first time
- UseEffect dependencies exist when they change
Let’s modify the counting example above to better understand the two hooks.
Edit on CodeSandbox
function Demo(props) {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
useEffect((a)= > {
const timer = setTimeout((a)= > {
setCount(step + count);
}, 1000)
return (a)= > {
clearTimeout(timer);
}
}, [count]);
return (
<div>
<div>Count: {count}</div>
<div>Step: {step}</div>
<button
onClick={()= > {
setCount(count + 1);
}}
>
Click
</button>
</div>);
}
Copy the code
In the Gif, when the Step size is updated, the count is still +1 the first time, and then +2.
- in
step
Updated,useEffect
thecount
There are no changes, so no updates are triggered useEffect
When triggered, the temporary data in Hook is used, so the step sizestep
Still is 1.
We supplement the process of comparison on the Hook loading process.
The Hook stores a snapshot value from the last render, so the value from the last render will also be used during execution.
Here, we summarize the rendering flow of function components
3. Summary
This article only mentions use estate and useEffect, which are two typical React Hooks.
Using useState as an example, we saw how React Hooks solve the problem of not retaining internal data inside function components.
Using effect, see how React Hooks handle timing between data -> views
And a very superficial mention of the Hook data temporary storage (snapshot) reason
React Hooks are used in many other ways, but this chapter is just a review of the basic concepts of React Hooks.
PS: The next chapter will focus on “How to reorganize and Encapsulate Yourself in Business.”
4. Refer to the Reference
React Hook analysis – The wind blows the old good boy article – Zhihu