Why does React have hooks

  1. The logic of data processing cannot be reused between components, or is not straightforward enough, such as the implementation of props and higher-order components

  2. Complex components are increasingly difficult to understand and maintain, and bugs are easy to introduce

  3. The Class syntax introduces complexity

What is the hook

  • A Hook is a special function that allows you to embed React features such as lifecycle, state, etc.

Basic rules for hook use

  1. A function can only be called on its outermost layer

  2. Hooks can only be called in React function components

  3. Custom hook naming convention (useSomething)

When to use hooks

  • If you were writing a function component and realized you needed to add some states to it, you would have to convert the rest to classes. Now you can use hooks in existing function components

Suggestions on using useState Hook

  • It is recommended to separate the different states and update them separately

useEffect

  • Run some additional features after React DOM updates (subscribe, send network requests)

  • Classification (side effects that need to be cleared and do not need to be clarified)

Important features

  • UseEffect is performed by default after each render, including the first rendering

  • A function passed to useEffect that returns a function will be executed when the component is destroyed to perform effect’s cleanup

  • To perform an effect that runs only once (only when the component is mounted and unmounted), you can pass an empty array as the second argument to useEffect

Customize the hook

  • Fixed the React component’s inability to share logic flexibly

  • Custom hooks start with use

  • The same hook does not share state

Hook api

  • Zh-hans.reactjs.org/docs/hooks-…

Refer to the article

  • Reactjs.org/docs/hooks-…