React Expansion 3-Hooks

1. What are React Hooks/Hooks?

Hook is a new feature/new syntax added to React 16.8.0, which allows you to use state and other React features in function components

2. Three commonly used Hooks

  • State Hook: React.useState()
  • Effect Hook: React.useEffect()
  • Ref Hook: React.useRef()
State Hook
  1. State Hook allows function components to also have a state state, and perform read and write operations on state data

  2. Syntax: const [xxx, setXxx] = React.useState(initValue)

  3. useState() description:

    • Parameters: The value specified for the first initialization is cached internally
    • Return value: an array containing 2 elements, the first is the internal current state value, and the second is the function to update the state value
  4. There are two ways to write setXxx():

    • setXxx(newValue): The parameter is a non-function value, directly specify the new state value, and use it internally to overwrite the original state value

    • setXxx(value => newValue): The parameter is a function, which receives the original state value and returns the new state value, which is used internally to overwrite the original state value

Effect Hook

(1). Effect Hook allows you to perform side-effect operations in function components (used to simulate life cycle hooks in class components) (2). Side-effect
operations in React:
send ajax request data acquisition
, set subscription/start timer
manually Change the real DOM
(3). Syntax and description:
useEffect(() => { // Any operation with side effects can be performed here return () => { // Executed before the component is unmounted // Do some finishing work here, Such as clearing timers/unsubscribing, etc. } }, [stateValue]) // If [] is specified, the callback function will only be executed after the first render()




(4). The useEffect Hook can be regarded as a combination of the following three functions:
componentDidMount()
componentDidUpdate()
componentWillUnmount()

Ref Hook

(1). Ref Hook can store/find tags or any other data in the component in the function component
(2). Syntax: const refContainer = useRef()
(3). Function: save the tag object, the function is the same as React.createRef( )Same

Guess you like

Origin blog.csdn.net/m0_55990909/article/details/124377326