4
头图

join us!

160fa4cdb54c62 " , provides technical-related information and a series of basic articles for front-end developers. For a better user experience, please move to our official website novices (160fa4cdb54c85 https://xhs-rookies.com/ ) to learn and get the latest articles in time.

"Code tailor" , if you are interested in our article or want to make some suggestions, follow "Novices of Xiaohe Mountain" public account, contact us, you can also watch it on WeChat Our article. Every suggestion or approval is a great encouragement to us!

Why should we learn hooks

Introduction to React-Hooks

Why does react have a hook?

1. The reuse of stateful class components is too troublesome

react is to split a page into a pile of independent, reusable components, and connect these components in a top-down unidirectional data flow. react in a large work project, you will find that many react components in your project are actually lengthy and difficult to reuse. Especially those class components, which contain state , are difficult to reuse.

official recommended solution

  • rendering attribute -Use a function value of prop nodes or component that needs to be dynamically rendered. As shown in the code below, we can see that our Provider component contains all the code related to the state, while the MyComponent component can be a simple Display components, so that Provider can be reused separately
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 .

Of course, under normal circumstances, it will be written in the following way:

<Provider>{(data) => <Cat target={data.target} />}</Provider>
  • HOC high-order component -a function accepts a component as a parameter, after a series of processing, finally returns a new component. Look at the following code example, withUser function is a high-order component, it returns a new component, This component has the function it provides to obtain 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)

The above two modes look pretty good, and many libraries also use this mode, just like our commonly used React-router library. But these two modes will increase the hierarchical relationship of the code. For obvious performance, you can install and open React Devtools look at the component nesting of the code. You will find that there are too many nesting times.

And if we use hooks , it will be much more concise and there is no extra level of nesting. hook the various functions you want into a reusable custom 060fa4cdb553c2, when you want to use any function of the component, you can hook

2. The logic in the life cycle function is more complicated

We usually want a function to only do one thing, but our life cycle hook function usually does many things at the same time. For example, we need componentDidMount , bind some event monitors, and so on. At the same time, sometimes we need to do the same thing again componentDidUpdate

When our page or this component becomes complicated, the content inside will increase, and the clarity of the logic will decrease.

3. This in class points to the problem

When the parent component passes the function to the child component, it must be bound to this

  • react components of four kinds of bindings this difference method
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>
    )
  }
}
  • Bind this constructor, then every time the parent component is refreshed, if the other props values passed to the child component remain unchanged, then the child component will not be refreshed
  • render() function is bound to this : Because the bind function returns a new function, a function will be regenerated every time the parent component is refreshed. Even if the parent component passes to the child component and the other props values remain unchanged, the child component will always Refresh
  • ()=>{} arrow function: when the parent component is refreshed, even if the function body of the two arrow functions is the same, a new arrow function will be generated, so the child component will be refreshed every time;
  • uses static properties of the class: the principle is similar to the first method, and it is more concise than the first

In summary, if you do not pay attention, it is easy to write the third way, resulting in performance loss

Advantages of hooks

  • There are problems with optimizing components
  • Can reuse state logic without modifying the component structure ( custom Hooks )
  • Ability to split the interrelated parts of the component into smaller functions (such as setting up a subscription or requesting data)
  • side-effect separation of concerns : side-effects refer to logic that does not occur in the process of data to view conversion, such as ajax request, access to native dom elements, local persistent cache, binding/unbinding events, adding subscriptions, setting timing , recorder, log, etc. In the past, these side effects were written in the life cycle function of the class component. useEffect will be executed after all rendering is completed, and useLayoutEffect will be executed after the browser layout and before painting

summary

Now, we have a general understanding hooks

Then we will start our basic hooks tutorial.

In the hooks series, we mainly introduce the commonly used hooks in four projects: useState , useEffect , useRefs , 160fa4cdb55a51,

If you want to know some of the other hook function ( useContext , useReducer , useMemo , useImperativeMethods , useMutationEffect , useLayoutEffect ), you can go official website to see .

Preview of the next section

In the next section, we will introduce useState to everyone, so stay tuned!


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。