How to use hooks in react

Time:2022-6-10

useState

const [ count ,setCount] = useState(parameter)
  • Count saves the parameters in usestate. The parameters can be ordinary parameters, function and array. If there are no parameters, they are undefined
  • Setcount is used when changing the value in count
  • Hooks can only be used in react function components or custom hooks, not directly in JS functions
  • Usestate should not be called in the loop, condition judgment or sub function, because the data saved in usestate is saved using the data structure of the linked list. Using usestate under the above conditions will break the linked list and confuse the data
  • In react hook functions and composite events, it is asynchronous
  • It is synchronous in setTimeout, setinterval and DOM native events

useEffect

useEffect(() => {
    console. Log ('Start subscription ')
    return () => {
      console. Log ('unsubscribe ')
    }
  }, [count])
  • It is mainly used to simulate the life cycle in class components. A function needs to be passed in. The function body is similar to the componentdidmount function in class components. Return returns a function, similar to the componentwillunmount function in class components. We can subscribe to certain events in the function body and unsubscribe from events in the return function
  • Hook can add multiple same hook functions, which means that instead of putting all subscription events and network requests in class components into componentwillunmount, you can use the same hook to extract different events
  • The second parameter of useeffect is an array, which mainly contains some variables in the function body. When these variables change, the function will be re executed. If you do not want to rely on any variables, just pass in an empty array

useContext

There are two ways to use shared context in components
  • Class components can be defined by class name Contexttype = mycontext method, get the context in the class
  • Multiple contexts or through mycontext Sharing context in consumer mode
  • When there are multiple contexts, there will be a lot of nesting

Context hook allows us to directly obtain the value of a context through hook

Const maincontext = usecontext (maincontext) // directly obtain the passed in value value 
  //Simplify the context to obtain the value. You can obtain the passed in value directly through usecontext
  //But the first step is still necessary
  const usecontext = useContext(Usecontext)
  console.log(maincontext, usecontext)

useReducer

  • Usereducer is mainly used to replace usestate in case of the same event and different methods to avoid too many usestate methods
  • Note that usereducer replaces usestate, not redux. The states in usereducer cannot be shared
import React, { useState, useReducer } from 'react'

function reducer(state, action) {

  switch (action.type) {
    case "add":
      return { ...state, count: state.count + 1 };
    case "sub":
      return { ...state, count: state.count - 1 }
    default:
      return state
  }
}
export default function Home() {
  // const [count, setCount] = useState(0)
  Const [state, dispatch] = usereducer (reducer, {count: 0}) // split usestate
  //Unified management of state change
  return (
    <div>
      <h2>Current count: {state.count}</h2>
      <button onClick={e => dispatch({ type: "add" })}>+1</button>
      <button onClick={e => dispatch({ type: "sub" })}>+1</button>
    </div>
  )
}

Usecallback and usememo

  • These two functions are the same, both forA function or object whose subcomponent passes the same contentDo not re render subcomponents when
  • The difference is that what usecallback passes in is a function, and corresponding dependencies can be added
Const sub = usecallback (/// subcomponents will not be re rendered without data changes
    () => {
      console. Log ("sub is executed")
      setCount(count - 1)
    }, [count],
  )
  • Usememo can return objects, arrays, functions, or add corresponding dependencies
//Object returned
  const info = useMemo(() => {
    return { name: "jack", age: 18 };
  }, []);

useRef

There are two common uses of ref

  • Usage 1: introduce DOM (or component, but class component) elements
  • Usage 2: save a data. This object can be saved unchanged throughout its life cycle
import React, { useRef, useState, useEffect } from 'react'

export default function UseRefDemo1() {
  const divRef = useRef()
  const iptRef = useRef()
  const [count, setCount] = useState(0)
  Const countref = useref (count) // only the initial value can be maintained,
  Useeffect (() = > {// use useeffect to save the last value
    countRef.current = count
  }, [count])
  function changeBtn() {
    divRef.current.innerHTML = "world"
    iptRef.current.focus()
  }
  return (
    <div>
      <div ref={divRef}>hello</div>
      <input ref={iptRef} type="" name="" />
      <button onclick={e = > changebtn()} > Click </button>
      <h2  >CountRef:{countRef.current}</h2>
      <h2>count: {count}</h2>
      <button onClick={e => setCount(count + 1)}>+1</button>
    </div>
  )
}

useImperativeHandle

To understand the usage of useimperativehandle, let’s take a look at the combination of ref and forwardref

  • Forward refs can be used to forward refs to child components
  • The child component gets the ref created in the parent component and binds it to one of its own elements
import React, { forwardRef, useRef, useImperativeHandle } from 'react'
//The parent component establishes contact through ref, and the child component receives ref through forwardref
const Btn = forwardRef((props, ref) => {
  const forwardRef = useRef()
  //Next, you need to use the refs of sub components
  return <input ref={forwardRef} type="text" />
})
export default function RefDemo() {
  const btnRef = useRef()
  return (
    <div>
      <Btn ref={btnRef} ></Btn>
      <button onclick={e = > btnref. Current. Focus()} > Click </button>
    </div>
  )
}
  • This example shows the combined use of ref and forwardref. It seems that there is no problem, but it is not rigorous enough. The parent component can get not only the focus method of the child component, but also other methods. However, only the focus method is needed here. React creates a useimperativehandle method to make the code more rigorous. This method is mainly to make the parent component get only the methods it wants, Other unnecessary methods do not need to be exposed to sub components. Here is a more rigorous way to write the above code
import React, { forwardRef, useRef, useImperativeHandle } from 'react'
//The parent component establishes contact through ref, and the child component receives ref through forwardref
//The useimperativehandle action only exposes the child component methods and properties required by the parent component
const Btn = forwardRef((props, ref) => {
  const forwardRef = useRef()
  useImperativeHandle(ref, () => ({
    Focus: () = > {// the parent component only needs the focus method, and only the child component's focus method is exposed
      forwardRef.current.focus();
    }
  }), [forwardref.current] // re render when the refs of sub components are updated
  //Next, you need to use the refs of sub components
  return <input ref={forwardRef} type="text" />
})
export default function RefDemo() {
  const btnRef = useRef()
  return (
    <div>
      <Btn ref={btnRef} ></Btn>
      <button onclick={e = > btnref. Current. Focus()} > Click </button>
    </div>
  )
}

-Here, the sub components only expose the focus method, and other methods are not exposed, which makes the logic of the code more rigorous

useLayoutEffect

  • Uselayouteffect looks very similar to useeffect. In fact, they are only a little different

    How to use hooks in react

    useLayoutEffect
  • Useeffect will be executed after the rendered content is updated to the DOM, and will not block the DOM update
  • Uselayouteffect will be executed before the rendered content is updated to the DOM, which will block the DOM update
  • If we want to update the DOM after some operation, we should put this operation into uselayouteffect