Weekend with React hooks
What is Hooks?
Hooks is a special kind of function inside a React function component (usually starting with "use", such as "useState"), enabling developers to still use state and life-cycles in function components, and reuse custom logic to reuse business logic.
As you know in React, the function component is a pure render component with no state and component life-cycle. If you need either of these two, the function needs to become a class component. Under the existing React API, this pattern has the following disadvantages:
- High degree of coupling between components, bloated component trees
In the existing mode, React's inter-component communication is nothing more than two kinds, one is a single data stream, and the other is to achieve global state and decoupling between components through a global store such as redux. When some states are not suitable for the global store, the reuse and communication of logic between components becomes very difficult (it must be passed down one layer at a time). This is especially true in Higher order components and render props. In order to reuse some logic, we created a lot of HOC (high-level components) to pass the state down. The problem with this is that as our application becomes larger and larger, there are more and more irrelevant wrapper components, and the React component tree becomes more and more bloated (you can even see dozens of layers in devtool). Wrapper). In some business scenarios, three or four additional components are nested inside a Tooltip component, making development and debugging less efficient.
In the new React hook, we can create a custom hook in which to reuse some logic that no longer appears in the component tree, but instead becomes a separate, independent logical unit, but they still respond to React in rendering. Change between.
- The confusion of the JavaScript class
Remember that when you first started JavaScript, one of the important difficulties that needs to be overcome is the "this" point, and the prototype chain, which inherits these problems. Even if we really understand the principle, in the daily development, it is inevitable to step on the pit because of negligence. This series of problems makes the newcomer relatively difficult to get started with React. For a simple example, the event listener in the React component needs to manually bind this before, which is hard to explain to a newcomer to JavaScript.
And this series of questions will be greatly solved in Hook. If there is no class and there is no this, then all of the above problems are no longer a problem.
Write Hooks
Having said that, what is the Hooks API? The first thing to declare is that Hooks are backward compatible and the class component will not be removed. As a developer, you can slowly migrate to this new API.
There are three main types of Hooks:
- State hooks (use state in function component)
- Effect hooks (use lifecycle and side effect in function component)
- Custom hooks (custom hooks are used to reuse component logic to solve the problems described in the first motivation above. This part is not covered in this much more space, please move the documentation).
State hooks
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"const [count, setCount] = useState(0);
return (
<div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>
Click me
</button></div>
);
}
As discussed before that hooks are essentially a special function (usually starting with "use"). Here, "useState" is a hook through which we can embed the state inside the component. This function returns a pair, the first value is the state value corresponding to the current hook, and the second is how to update the value.
We can feel from it that the previous usages of the two return values are:
- This.state
- this.setState
In addition to this, we can also use multiple useStates in a function component:
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [cname, setcname] = useState('Enquero');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
One of the great benefits of this is that we can avoid the component's state structure being too bloated (because each component class can only have one state), and it can handle each state independently. Another benefit is that this is very intuitive, and you can see two variables related to this state at a glance, such as [age, setAge].
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser APIdocument.title = `You clicked ${count} times`;
});
return (
<div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>
Click me
</button></div>
);
}
We also need to solve a problem, that is, how to use life-cycles, life cycle functions in the function component. Here, all life-cycles, such as componentDidMount, componentDidUpdate, shouldUpdate, and so on, are grouped into a Hook called useEffect. This function is similar to subscribe in redux. When React is re-rendered due to state or props, it triggers the callback listener in useEffect (triggered after the first render and each update).
Why is it called useEffect? Because many of the operations we usually do in the life cycle will produce some side-effect operations, such as updating DOM, fetch data, and so on.
In addition to useState, useEffect has other hooks that come with React. such as:
useContext
Instead of <Context.Consumer> using render props, the component tree is more concise.
useReducer
Equivalent to the redux reducer that comes with the component, it is responsible for receiving the dispatch dispatch action and updating the state.
Please see the documentation for detailed usage.
Hope this helped you to understand . why this new API is called "Hooks". Hooks are a series of special functions that enable the internal "functional component" to "hook" state and life-cycles inside React.
This backward-compatible API solves some of the existing problems, not only allows us to better use state and life-cycles, but the real power is to make it easier to reuse component logic (custom hooks) ). However, due to space limitations, many powerful parts and some precautions are not explained in this article. Please follow the official documentation to learn more detailed postures (wall crack recommendation).