current position:Home>26 [react basics-5] react hook

26 [react basics-5] react hook

2022-04-29 16:10:36X Beichen North

hook Significance of emergence

hook yes react 16.8 Knowledge added in version , The purpose of its appearance is to enable us to use the features only found in many class components in function components , for example state、 Life cycle, etc .

 

hook brief introduction

hook To put it bluntly, it's actually some react Special functions in , It's just that these functions allow us to hook in some react Characteristics of , For example, we want to use... In function components state You don't have to turn it into a class component , Use it directly useState() This hook Function ; If you want to use these functions in a function component similar to the life cycle of a class component , Use it directly useEffect() This hook function ……

 

useState Hook

useState() This hook Functions allow us to use... In function components state.

Its usage is as follows :

  1. introduce react Medium useState Hook;
  2. By calling useState() Make a statement state Variable and how to modify this variable ;
  3. Render the variable data where the page needs to be , Call the method of modifying variables where the page needs to be updated to update the page .
import React, { useState } from "react";  // Corresponding to the first step 

const StateHook = () => {
  const [count, setCount] = useState(0);  // Corresponding to step 2 

  return (
    <div>
      <p>you click {count} times.</p>  // Corresponding to step 3 , Using variables 
      <button onClick={() => setCount(count + 1)}>click</button>  // Corresponding to step 3 , modify 、 Update variables 
    </div>
  )
}

export default StateHook;

useState() Function details :

  • useState() Returns an array containing two elements , The first element of the array is a value , The second element is a function ;
  • stay useState() On the left side of the function, the operation of array deconstruction and assignment , Assign the first element returned to the declared variable count, Assign the second element to the declared setCount. here count and setCount The name of is custom , You can call it whatever you want ;
  • useState() The function has only one argument , This parameter is the initial value of the variable declared on the left , It can be a number 、 character string 、 Object etc. ;
  • If you want to define multiple state, You only need to call useState() that will do .

As can be seen from the above useState Hook As defined in the class component state、 Read state、 to update state The difference is as follows :

1、 Definition state

useState Hook:

const [count, setCount] = useState(0);

Class component :

constructor(props) {
  super(props);
  this.state = {      
    count: 0    
  };  
}

2、 Read state

useState Hook:

<p>you click {count} times.</p>

Class component :

<p>you click {this.state.count} times.</p>

3、 to update state

useState Hook:

<button onClick={() => setCount(count + 1)}>click</button>

Class component :

<button onClick={() => this.setState({ count: this.state.count + 1 })}>click</button>

 

useEffect Hook

useEffect() This hook Allows us to use features like lifecycle in functional components , To be precise , It allows us to perform side effects in function components .

Its usage is as follows :

  1. from react Introduction in useEffect Hook;
  2. In a function component, call useEffect() To perform a side effect .
import React, { useState, useEffect } from "react";  // Corresponding to the first step 

const EffectHook = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {  // Corresponding to step 2 
    document.title = `click ${count} times`;
  })

  return (
    <div>
      <p>you click {count} times.</p>
      <button onClick={() => setCount(count + 1)}>click</button>
    </div>
  )
}

export default EffectHook;

useEffect() Function details :

  • useEffect() Similar to... In class components componentDidMount、componentDidUpdate、componentWillUnmount The combination of three life cycles ;
  • useEffect() The parameter passed in is a function , This function is called a effect, This function tells react At the first time DOM What side effects should be performed after rendering and each update , For example, data acquisition 、 modify DOM Content, etc. ;
  • useEffect() By default, the first time DOM After rendering and every update ;
  • If you want to eliminate some side effects , For example, unbinding events 、 Unsubscribe, etc , You can pass in useEffect() Return a function in the function of , In this function, the operation of eliminating side effects , as follows :
useEffect(() => {
    // Executive side effects 
    document.title = `click ${count} times`;
    return () => {
      // Eliminate side effects 
      // The method here will be executed when the component is unloaded 
      //some code...
    }
})
  • react At each execution of the current effect I'll be right about the last time effect Scavenging , So we can see that the function to eliminate side effects in the above code will execute every time , But what it gets internally count The value is the last value ;
  • useEffect() There is a second optional parameter , If you want to make the current effect Only once , The second parameter passes in an empty array ; If you want to make the current effect Follow a state Make an execution call , The second parameter passes in a specific state.

 

Hook Usage rule

1、 Use only at the top level hook

  • Don't cycle 、 Use... In conditions or nesting hook

2、 Only in react Call in function hook

  • stay react Call in function component hook
  • In the custom hook The other is called hook

 

Customize hook

Customize hook In fact, it is a function that realizes the reusability of component logic , But the function name must be with “use” It's just the beginning .

Customize hook Generally, it is highly related to the business needs of our project , We can pull out some reusable logic in the component , Implement some custom hook.

 

Others hook

Here are some that are less frequently used in normal development hook:

name

effect

useState

You can use... In function components state.

useEffect

Side effects can be used in function components .

useContext

Read context Value , subscribe context The change of .

useReducer

useState alternatives , Follow redux Medium reducer similar .

useCallback

Cache function reference .

useMemo

Cache the value of the function .

useRef

Return the same... Every time you render ref object .

useImperativeHandle

Can be used in ref Customize the instance value exposed to the parent component .

useLayoutEffect

You can use it to get DOM Layout , And trigger re rendering synchronously .

useDebugValue

react Show custom in developer tools hook label .

 

 

copyright notice
author[X Beichen North],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291427264189.html

Random recommended