Come and join us!
“The Newbies of Little and Hill” provides technical information and a series of basic articles for front-end developers. For a better user experience, please move to our official website of Xiaoheshan beginners (https://xhs-rookies.com/) to learn, timely access to the latest articles.
“Code tailor”, if you are interested in our articles or would like to make some suggestions, please follow our official account “newbies of Xiaoheshan” at WeChat, and contact us. You can also view our articles on WeChat. Every suggestion or agreement is a great encouragement to us!
Why do we learn hooks
A brief introduction the React – Hooks
Why does act have a hook?
1. The reuse of stateful class components is too troublesome
The core idea of React is to break a page down into a bunch of independent, reusable components and chain them together in a top-down one-way data stream. But if you use React on a large work project, you’ll find that many of the React components in your project are actually long and hard to reuse. In particular, Class components, which contain states themselves, are difficult to reuse.
Official recommended solution
- Rendering attributes– Use a value as a function
prop
To pass the ones that need to be rendered dynamicallynodes
You can see our code belowProvider
The component contains all the code related to state, andMyComponent
The component can be a simple display component, in this caseProvider
I can reuse it alone
import MyComponent from 'components/myComponent'
class Provider extends React.Component {
constructor(props) {
super(props)
this.state = { target: 'MyComponent' }
}
render() {
return <div>{this.props.render(this.state)}</div>
}
}
<Provider render={(data) => <MyComponent target={data.target} />} />
This mode is called render-props.
Usually, of course, it will be written like this:
<Provider>{(data) => <Cat target={data.target} />}</Provider>
- Hoc high-order components– A function takes a component as an argument, processes it, and returns a new component. Take a look at the following code example,
withUser
The function is a higher-order component that returns a new component with the functionality it provides for retrieving user information.
const withUser = (WrappedComponent) => { const user = localStorage.getItem('user') return (props) => <WrappedComponent user={user} {... props} /> } const UserPage = (props) => ( <div class="user-page"> <p>I'm the user, {props.user}! </p> </div> ) export default withUser(UserPage)
Both of these patterns look good, and many libraries use them, such as the React -Router library. Both patterns, however, increase the hierarchy of the code. To make this obvious, open the React DevTools installation and look at the nesting of components in your code, and you’ll see that it’s nesting too many times.
If we use hooks, this is much cleaner, with no additional level nesting. Write each desired function as a reusable custom hook. When your component wants to use a function, call the hook directly from within the component.
2. The logic in the life cycle function is relatively complex
We usually want a function to do one thing, but our lifecycle hook functions usually do many things at the same time. For example, we need to make a request in ComponentDidMount to get the data, bind some event listeners, etc. Also, sometimes we need to do the same thing again at ComponentDidUpdate.
As our page, or our component, becomes more complex, the content becomes more and the logic becomes less clear.
3. This in the class refers to the problem
When a parent passes a function to a child, it must bind this
react
There are four bindings for components inthis
Differences in Methods
class App extends React.Component<any, any> {
handleClick2
constructor(props) {
super(props)
this.state = {
num: 1,
title: ' react study',
}
this.handleClick2 = this.handleClick1.bind(this)
}
handleClick1() {
this.setState({
num: this.state.num + 1,
})
}
handleClick3 = () => {
this.setState({
num: this.state.num + 1,
})
}
render() {
return (
<div>
<h2>Ann, {this.state.num}</h2>
<button onClick={this.handleClick2}>btn1</button>
<button onClick={this.handleClick1.bind(this)}>btn2</button>
<button onClick={() => this.handleClick1()}>btn3</button>
<button onClick={this.handleClick3}>btn4</button>
</div>
)
}
}
- In the constructor
this
Every time the parent component refreshes, if passed to the child component otherprops
If the value is unchanged, the child component will not refresh render()
Function inside bindingthis
Because:bind
The function returns a new function, so each time the parent component refreshes, a function is regenerated, even if the parent passed something else to the child componentprops
The value is unchanged, and the child component is refreshed every time;() = > {}
Arrow function: When the parent component refreshes, a new arrow function is generated even if the body of the two arrow functions is the same, so the child component refreshes each time.- Using static properties of a class: The principle is similar to the first approach, and is simpler than the first
In summary, if you’re not careful, it’s easy to write it the third way, resulting in a performance penalty
Advantages of hooks
- There are problems with being able to optimize class components
- Ability to reuse state logic without modifying the component structure (custom Hooks)
- The ability to break the interrelated parts of a component into smaller functions (such as setting subscriptions or requesting data)
- Separation of concerns for side effects:Side effects refer to logic that does not occur during the data-to-view transformation, such as
ajax
Request, access nativedom
Element, local persistent cache, bind/unbind events, add subscriptions, set timers, log, and more. Historically, these side effects were written in class component lifecycle functions. whileuseEffect
It will not be executed until the rendering is complete.useLayoutEffect
It will be in the browserlayout
After that,painting
Before execution.
summary
Now we have a general idea of hooks.
From there we will begin our basic hooks tutorial.
In this series of hooks, we focus on four hooks that are commonly used in projects: useState, useEffect, userEFS, and useCallback.
If you want to learn about some of the other hook functions (UseContext, UserEduer, UseEmo, UseImperativeMethods, UseMutationEffect, UseLayouteffect), you can check them out on the website.
Next day forecast
In the next section, we will introduce you to UseState. Stay tuned!