Purpose: The purpose of Hooks is to add state to functional components

useState

const [value, setValue] = useState(initValue)

  • valueIs status data
  • setValueFunction for changing data
  • initValueIs the initial value of the status data

React does not provide an overloading of setValues, so multiple setvalues are executed only once in a row and asynchronously. useEffect

useEffect

What is a pure function? React: Pass in the same parameters (props) and render the same UI forever

What are side-effects? In contrast to pure functions, components handle things that have nothing to do with return (rendering logic), or that can render a different UI with the same parameters. AJAX, conso.log, changing global variables and so on can all be side effects,

  • Asynchronous execution
  • UseEffect can be seen ascomponentDidMount,componentDidUpdateandcomponentWillUnmountThe combination of
  • Don’t worry about iteffectDependency expiration conditions. Every time we re-render, it generatesThe new effectTo replace the previous one.

UseEffect can be passed a second argument of type array. At this point, the effect function is executed only if the values in the array change. Otherwise, skip this function run. What happens if you pass an empty array? So useEffect is equal to componentDidMount. Only executed on the first component rendering. This situation can be used for Ajax fetching data (do not use the default for fetching data (do not pass the second parameter), otherwise Ajax requests will be sent an infinite number of times)

UseEffect cannot be an async function, so what if I still want to use async await? You can create a new async function inside the effect function and call it

useContext

Used to transfer values to grandparent and grandparent components. How to use it?

  1. Creating context objects
    export const appContext = React.createContext(value)
Copy the code

Value is the object to be passed. Note that export should be exported because descendant components need to reference 2. ** Wrap the child component with the Provider component that created the context. For example, the global supply value **

    <appContext.Provider value={value}>
        <app />
    </appContext.Provider>
Copy the code

3. Introduce context objects in descendant components,

  • The Consumer component of the context object is used in the class component, with its wrapped function parameters as the values provided by the Provider.
  • Use useContext in function components

    import { appContext } from '... '
    
    / / class components.// jSX/ TSX
    return (
      <appContext.Consumer>
      {(value) => {
          return (
              ... // jsx/tsx
          )
      }}
      </appContext.Consumer>
    )
   
   // Function components
   const value = useContext(appContext) // Arguments are context objects. Now you can use value directlyCopy the code

.