concept

Some functions that “hook” into function components with features like React State and lifecycle.

Why Hook is chosen

1. Reuse state logic without modifying component structure
  • Class components: Reuse state logic is very complex, such as high-level components, context, render props, etc., need to adjust the layout logic; And if the hierarchy is too deep, it’s easy to create “nested hell.”
  • Hook: Can extract reuse state logic without modifying component structure.
2. Use Effect to solve complex life cycle and function processing
  • Class components: There may be a lot of logic in the same life cycle, such as requesting data in componentDidMount, setting event listeners, timers, etc., and then clearing it in componentWillUnmount. Completely unrelated logic is grouped in the same method, and the related logic is fragmented and difficult to maintain.
  • Hook: Built-in processed life cycle, no need for manual maintenance, Effect Hook implements granular function logic, can split different functions, such as interface request, subscription setting, Dom operation, etc., execute different methods, do not need to divide according to life cycle; It also supports callback processing, such as unsubscribing or untiming, which can be performed within a callback with stronger logical relevance.
Delete the class concept
  • Class components: You need to understand and use this, and you need to distinguish the classification component from the function component; Class does not compress well, and thermal loading is unstable.
  • Hook: No need to use this, more function scheme.

Commonly used Hook

State Hook

  • You can use state in function components
  • Unlike the setState of the class component, useState does not automatically merge update objects and needs to be calculated using the update function setXxx

Effect Hook

  • mergecomponentDidMount,componentDidUpdate,componentWillUnmountThe life cycle
  • Functions assigned to useEffect, such as data fetching, subscription setting, Dom updating, etc., are executed after the component is rendered
  • The useEffect function returns a cleanup function that is executed before the component is uninstalled, such as the cleanup subscription, cleanup timing, and so on
  • If you want to run effect only once, you can pass an empty array [] as the second argument

other

  • useContext
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

Matters needing attention

  • It can only be called in the outermost layer of a function, not in loops, conditional judgments, or subfunctions. Ensure that hooks are called in the same order during multiple renders so that React can correctly associate the internal state with the corresponding Hook
  • Cannot be used in a class component

reference

More detailed React Hook:react.docschina.org/docs/hooks-…