Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

📢 Hello everyone, I am Xiao Cheng, a sophomore front-end enthusiast

📢 This article is a study note for the section on Learning React hooks

📢 Thank you very much for reading

📢 May you be true to yourself and love life

The meaning of which hooks exist

  1. The state between hooks is separate and has its own context; there is no state confusion

  2. Let the function have state management

  3. The component tree is not intuitive, class components are difficult to maintain, logic is not easy to reuse problems

  4. Avoid the side effects of repeated function execution

Application scenarios

  1. Replace life cycle functions with hooks
  2. Let the component have state
  3. Component helper function
  4. Processing send requests
  5. Access data
  6. Optimize performance

hooks API

We import it from React

1. useState

Adds state to function components

  • Initialize and update the component state
const [count, setCount] = React.useState(0)
Copy the code

Takes an argument as an initial value and returns an array: the first is the state variable, and the second is the function that modifies the variable

2. useEffect

Side effects of hooks

  • Add a signal to end rendering for components that have no life cycle

Note:

  • Hooks executed after render

The first parameter receives a function that is executed when the component is updated

The second argument takes an array of variables to track, a list of dependencies, and updates only when dependencies are updated

The return value of the first argument, which returns a function, is executed before useEffect is executed

It is generally used to add destruction events so that only one can be added

React.useEffect(() = > {
    console.log('Called');
    return () = > {
        console.log('I'm about to be unloaded.');
    }
}, [count])
Copy the code

print

3. useLayoutEffect

This is similar to useEffect

This is used to perform an operation after a DOM update is complete

Note:

  • Hooks with DOM manipulation side effects
  • Execute after DOM update

UseEffect is executed before useEffect. All other uses are the same as useEffect

UseEffect executes after Render

UseLayoutEffect is executed after DOM update

4. useMemo

Function: Allows a function in a component to follow status updates

Note: Optimize the function function in the function component

To avoid forced execution of the current function due to other status updates

The first argument takes a function, and the second argument, an array of dependencies, returns a value

const getDoubleNum = useMemo(() = > {
    console.log('ddd')
    return 2 * num
}, [num])
Copy the code

5. useCallback

Effect: Executes following status updates

Note:

  • It is executed only if the dependency changes
  • useMemo( () => fn, deps)The equivalent ofuseCallback(fn, deps)

Difference:

  1. useCallback It returns a function, not a value
  2. useCallbackThe cache is a function,useMemoThe cache is a value,If the dependency is not updated, the cached function is always returned
  3. To child componentspropsIf the current component is not updated, re-rendering of child components will not be triggered

6. useRef

Function: Save data for long time

Matters needing attention:

  • Returns an index of child elements that remains constant throughout the life cycle
  • Object changes are not notified, and property changes are not re-rendered
  1. Save a value that remains constant throughout its life cycle
  2. To assign a valueref.currentRerender will not trigger
  3. It creates an extra container to store the data, and we can get the value externally

When we get the id of the timer in the normal way, we cannot get it, we need to get it through ref

useEffect(() = > {
    ref.current = setInterval(() = > {
        setNum(num= > num + 1)},400)
}, [])
useEffect(() = > {
    if (num > 10) {
        console.log('It's ten');
        clearInterval(ref.current)
    }
}, [num])
Copy the code

7. useContext

What it does: Render with subcomponents

Note:

  • A change in the upper-level data will definitely trigger a re-rendering
  1. We need to introduceuseContext 和 createContextTwo content
  2. throughcreateContextTo create aContexthandle
  3. throughProviderDetermine the scope of data sharing
  4. throughvalueTo distribute the data
  5. In the child component, passuseContextTo get the data
import React, { useContext, createContext } from 'react'
const Context = createContext(null)
export default function Hook() {
    const [num, setNum] = React.useState(1)

    return (
        <h1>This is a function component - {num} // scoping<Context.Provider value={num}>
                <Item1 num={num} />
                <Item2 num={num} />
            </Context.Provider>
        </h1>)}function Item1() {
    const num = useContext(Context)
    return <div>Subcomponent 1 {num}</div>
}
function Item2() {
    const num = useContext(Context)
    return <div>Subcomponent 2 {num}</div>
}

Copy the code

8. useReducer

Purpose: To borrow resources from other places

Note: Function component’s Redux operation

  1. Creating a data warehousestoreAnd managersreducer
  2. throughuseReducer(store,dispatch)In order to getstate 和 dispatch
const store = {
    num: 10
}
const reducer = (state, action) = > {
    switch (action.type) {
        case "":
            return
        default:
            return}}const [state, dispatch] = useReducer(reducer, store)
Copy the code

Dispatch actions via Dispatch

9. Customize hooks

Put it in the utils folder and name it starting with use

For example: Hooks that simulate data requests

import React, { useState, useEffect } from "react";
function useLoadData() {
  const [num, setNum] = useState(1);
  useEffect(() = > {
    setTimeout(() = > {
      setNum(2);
    }, 1000); } []);return [num, setNum];
}
export default useLoadData;
Copy the code

Reduce code coupling

We want the Reducer to be used by each component, we write a hooks ourselves

Customize a LocalReducer of your own

import React, { useReducer } from "react";
const store = { num: 1210 };
const reducer = (state, action) = > {
  switch (action.type) {
    case "num":
      return { ...state, num: action.num };
    default:
      return{... state }; }};function useLocalReducer() {
  const [state, dispatch] = useReducer(reducer, store);
  return [state, dispatch];
}
export default useLocalReducer;
Copy the code
  1. Introduce React and the hooks you need
  2. Create your own hook functions
  3. Returns an array in which the first content is data and the second is a function that modifies the data
  4. Expose custom hook functions out
  5. Introduce your own business components