React Custom Hooks learn

Vue to React or just getting started with React. Look at the previous article
  1. React Hook Introduction, vs Vue
  2. React, Hook, React
  3. React Hook uses Context
Introduction to the

React Hooks are a new feature since Act 16.8. Functional programming after React relies on Hooks. The sample

import { useState, useEffect } from 'react'
const Watch = () = > {

    const [count, setCount] = useState(0)
    const [count1, setCount1] = useState(0)
    const updateCount = () = > {
        setCount(count + 1)}const updateCount1 = () = > {
        setCount1(count1 + 1)
    }

    useEffect(() = > { //* When data changes are triggered, the equivalent of Mounted will be executed after the first render and every update
        console.log(count)
    })
    return (
        <div>
            {count} - {count1}
            <button onClick={updateCount}>count++</button>
            <button onClick={updateCount1}>count1++</button>
        </div>)}export default Watch
Copy the code

In this code, useState and useEffect hooks are used to realize the counter function. If you have used class, you will find that the code is more concise than class after using Hook. We will describe their functions below.

The official Hooks

UseState: Used to create a variable

This is probably the most commonly used API, and is used to create a variable for the page response that can be used directly within the page. If you create a variable directly the page doesn’t respond when the variable changes. grammar

import { useState } from 'react'
const [state, setState] = useState(init)
Copy the code

The useState method passes in an initialized value and returns a state and a set method. The state of state can be changed only through the set method

UseEffect: Can be used as a lifecycle (componentDidMount, componentDidUpdate, componentWillUnmount)
useEffect(() = > { //* When data changes are triggered, the equivalent of Mounted will be executed after the first render and every update
        console.log(count)
    })
Copy the code
3. UseContext,useReducer can be used as the global storage of the component tree

React Hook uses Context

4. UseMemo receives a function and an array of dependencies, which are updated when the array of dependencies is modified. Can be used as a calculated property
import { useState,useMemo } from "react";

const Computed = () = > {
    //* Declare two states to be added
    const [count,setCount] = useState(1)
    const [count1,setCount1] = useState(1)

    //* Declare a calculated attribute value as the addition of two counts. The second parameter is the listening attribute. Pass [count,count1], call when the two values are modified, similar to API useCallback
    const total = useMemo(() = > {
        return count + count1
    },[count,count1])

    const addCount = () = > {
        setCount(count + 1)}const addCount1 = () = > {
        setCount1(count1 + 1)}return (<div>
        {count} - {count1} - {total}
        <button onClick={addCount}>count++</button>
        <button onClick={addCount1}>count1++</button>
    </div>)}export default Computed
Copy the code
5. UseCallback and useMemo, which can be used to prevent functions from being rendered repeatedly when there are too many states
const callback = useCallback(
  () = > {
    
  },
  [a, b],
);
Copy the code

Only when a and B are modified will a new function todo be generated and need to be retested

6. UseRef returns a ref object placed in the element that can be used to get the DOM operation todo
import React, {useRef} from "react";
import Com from './components/com';

const Ref = () = > {
    const myRef = useRef();
    const getRef = () = > {
        console.log(myRef,'ref');
        
    }
    return (<div>
        <Com ref={myRef} text="Content" />
        <button onClick={getRef}>Get ref</button>
    </div>)}export default Ref;
Copy the code
UseImperativeHandle customizes methods and attributes exposed to the parent component to be used in conjunction with ref

The parent component

import Input from './components/Input'
import {useRef, useCallback} from 'react'
const Hooks = () = > {
    const inputRef:any = useRef({val:' '}) //* Create a ref object

    const handleClearInput = useCallback(() = > { //* Call the child component's clear methodinputRef.current.clear(); } []);const getRef = () = > {
          console.log(inputRef);
          
      }
    return (<div>
        <Input ref={inputRef}></Input>
        <button onClick={handleClearInput}>clear input</button>
        <button onClick={getRef}>Get ref</button>
    </div>)}export default Hooks
Copy the code

Child components

import { useState, useImperativeHandle, useCallback, forwardRef } from 'react'

const Input = (props:any, ref:any) = > {
    console.log(props);
    
    const [val, setVal] = useState('0')
    const clearInput = useCallback(() = > { / / * empty input
        setVal(' ')
    }, [])

    useImperativeHandle(ref, () = > ({ //* Using this API, you can customize the methods and properties exposed to the parent component
        val: val,
        clear: () = > {
            clearInput()
        }
    }))

    return (<input type="text" value={val} onChange={(e)= > setVal(e.target.value)} />);
}

export default forwardRef(Input) //* Encapsulate the ref hook
Copy the code
8. UseEffect of synchronous version of useLayoutEffect
import { useState,useMemo, useLayoutEffect } from "react";
useLayoutEffect(() = > {
    console.log('Listening for data modification');
})
Copy the code

This is not recommended because it is called synchronously after Dom updates. Using it to change DOM properties may result in no transition effect

9. UseDebugValue is used to develop custom Hooks for debugging
useDebugValue(
  size.width < 500 ? '---- size.width < 500' : '---- size.width > 500'
);
Copy the code

You can view the output in React DevTools.

Customize the Hook

In addition to official Hooks, users can customize Hooks to increase code reusability. Custom hooks must start with use. Other hooks can be used in custom hooks. \ Below is a custom Hook demo, implement the function of the timer custom.ts(Hook file)

import { useState } from "react";

const useCount = () = > {
    const [count, setCount] = useState(0)
    const add:any = () = > {
        setCount(count+1)}const subtract:any = () = > {
        setCount(count-1)}return [count, add, subtract]
}

export default useCount
Copy the code

The page references hooks, which is a folder I created myself

import useCount from "hooks/custom"

const Custom = () = > {
    const [count,add,subtract] = useCount()
    return (<div>Quantity: {count}<button onClick={()= > {add()}}>add</button>
        <button onClick={()= > {subtract()}}>subtract</button>
    </div>)}export default Custom
Copy the code

Here are some custom Hooks found on the web, which will continue to be updated with the ##### reference link

  1. 15 useful custom React Hooks