React hook | 9 necessary hooks

Time:2021-10-24

React hook guide

What is hook?

HookIt is a new feature of react 16.8. It allows you to use state and other react features without writing class.

HookIn essence, it is a function, which simplifies components and has its own state management, life cycle management and state sharing.

  • useState
  • useEffect
  • useContext
  • useReducer

What did hook solve?

  • [] state reuse between components. For example, using usecontext can solve the problem of state reuse, or customize HookTo customize the state management that meets your business scenario.
  • [] use the life cycle in function components to better design and encapsulate components. You cannot directly use the life cycle in a function component HookThis problem is well solved.
  • [] for the difference between function component and class component, we should also distinguish the use scenarios of the two components. use HookDon’t think about it at all. It can use more ReactNew features.

When to use hook?

  1. Called at the top level of a function component

  2. Use / customize in functions HookUsed in

React Built in Hook

    1. useStateState management
    1. useEffectLife cycle management
    1. useContextShared status data
    1. useMemoCache value
    1. useRefGet DOM operation
    1. useCallbackCache function
    1. useReducerRedux similar
    1. useImperativeHandleSub component exposure value / method
    1. useLayoutEffect Completing the side effect operation will block the browser drawing

useStateState management

stay classComponent, we get stateYes this.stateTo get it.

And inFunction componentYes, No thisYes, we can use HookProvided useStateTo manage and maintain state .

useState Definition / use

const [state, setState] = useState(initialState)

  • Setstate updates the sate method for
  • Usestate (initialstate) initialstate is the initial value

Intact chestnuts

import {useState} from 'react';

export default () => {
    Const [data, setData] = useState (WeChat official account: front-end self-learning community)
    return (
        <div>
            <h1>{data}</h1>
            {/ * update state * /}
            <button onClick={() =>{setData ('WeChat official account: front-end self learning community 666')}}></button>
        </div>
    )
}

useEffectLife cycle management

definition

useEffect Can be seen asFunctional componentLife cycle management.

Because the lifecycle cannot be used directly in functional components, it must be managed HookFor management.

useEffectThere are 3 lifecycle functions that can be used:

  • componentDidmount
  • componentDidUpdate
  • componentWillUnmount

No need to clear Effectuse

What does not need to be cleared Effect use?

After react updates the DOM, run some additional code

Then it is in the life cycle compoentDidmountand componentUpdateJust execute in.

useEffect(() => {
        //It will be executed by default  
        //This is equivalent to the class component life cycle
        //compoentDidmount    compoentDidUpdate
    }, [])

eliminateEffectuse

1. What is clearingEffect

When a component needs to be unloaded and some event processing needs to be performed, the class component life cycle is required componentUnmount .

stay useEffectIt is very convenient to use. You can return a method internally and write the corresponding business logic in the method

2. Why are you here EffectReturn a function in?

This is an optional cleanup mechanism for effect. Each effect can return a cleanup function. This brings together the logic for adding and removing subscriptions. They are all part of the effect.

useEffect(()=>{
        return () => {
            Console.log ('execute during component unloading ')
        }
    })

monitor statechange

You can monitor by control stateChange to implement the corresponding business logic.

useEffect(() => {
        //Listen for num and count status changes
        //Null [] or not write when not listening
    }, [num, count])

Intact chestnuts

import { useState, useEffect } from 'react';

export default () => {
    const [num, setNum] = useState(0)
    const [count, setCount] = useState(1)

    useEffect(() => {
        //It will be executed by default  
        //This is equivalent to the compoentdidmount compoentdidupdate of the class component life cycle
        console.log(`num: ${num}`)
        console.log(`count: ${count}`)

        //When the component is unloaded, the contents in return will be executed
        return () => {
            //Componentwillunmount equivalent to the class component life cycle 
            Console.log ('test ')
        }
    }, [num])

    return (
        <div>
            <h1>{num}</h1>
            < button onclick = {() = > {setnum (Num + 1)}} > Update num < / button >
            <hr />
            <h1>{count}</h1>
            < button onclick = {() = > {setcount (count + 1)}} > update count < / button >
        </div>
    )
}

useRef

What is? useRef ?

useRefWhat is returned is a variable ref object whose property current is initialized as the passed in parameter (initialvalue),The returned ref object remains unchanged throughout the life cycle of the component

effect:

  1. Get DOM operations, such as get input focus

  2. Get instances of child components (only class components are available)

  3. A global variable in a function component will not be declared repeatedly because of repeated render

Chestnuts

import {useRef} from 'react';


export default () => {
    const inputRef = useRef({value:0})
    return (
        <div>
            <h1>Testing</h1>
            <input type="text" ref={inputRef} />
            < button onclick = {() = > {console. Log (inputref. Current. Value)}} > get the input value < / button >
            < button onclick = {() = > {inputref. Current. Focus ()}} > get input focus < / button >
        </div>
    )
}

useContextStatus data sharing

ContextSolved what

In daily development, our parent-child components are through propsTo communicate if encounteredCross level component communicationThen we can’t pass propsHere we go.

At this time, you can think about how to share the component state for use?

  • Context
  • Redux
  • .....

This subsection was adopted ContextTo achieve component data sharing

What is? Context

Data sharing, any component can access context data.

stay ReactIn, component data is passed propTo transfer data from top to bottom. To transfer data globally, you can use Context .

be careful:

The main application scenarios of context arequite a lotComponents at different levels need to access the same data. Please use it with caution, because it will make the reusability of components worse.

establish Context

in use ContextIt must be created, and a separate file can be created for it to manage Context,

import React from 'react';

export const MyContext = React.createContext();

use Context

in use ContextIt is usually used in the top-level component (parent component) and can be enjoyed by the internal components wrapped by it stateUse and modification of.

adopt Context.ProviderTo wrap, the value passes value = {}Pass.

How are subcomponents used ContextThe value passed?

  • adopt useContext()Hook can easily get the corresponding value
// Context.js
import React from 'react';

export const MyContext = React.createContext();
import { useContext } from 'react';
import {MyContext} from '../Context/index'

const result = {
    code:200,
    Title: 'successfully added data'
}
const Son = () => {
    const res = useContext(MyContext)
    return (
        <>
            <div>
                <h1>{res.code}</h1>
                <hr/>
                <h2>{res.title}</h2>
            </div>
        </>
    )
}


export default  () => {
    return (
        <MyContext.Provider value={result}>
            <div>
                <h1>Front end self-study community</h1>
                <Son/>
            </div>
        </MyContext.Provider>
    )
}

useMemoImprove performance optimization

definition

useMemoIt is used for performance optimization to avoid high overhead calculation on each rendering by memorizing values.

useMemoParameters:

  • useMemoThe return value is memoized Value for caching
  • array control useMemoRe execute the array of ⾏,When the state in the array changesWill be re executed useMemo

be careful:

    1. Do not pass the array, and each update will be recalculated
    1. Empty array, only calculated once
    1. It depends on the corresponding value. When the corresponding value changes, it will be recalculated (it can depend on the value returned by another usememo)

Chestnuts

import { useState, useMemo} from 'react';


export default () => {
    const  [count, setCount] = useState(0)
    const [num, setNum] = useState(0)
    const newValue = useMemo(()=>{
        Console.log (` count value is ${count} `)
        Console.log (` num value is ${num} `)
        return count+num
    },[count])
    return(
        <div>
            <h1>{count}</h1> 
            <button onClick={()=>{setCount(count+1)}}>count + 1</button>
            <hr/>
            <h1>{num}</h1> 
            <button onClick={()=>{setNum(num+1)}}>Num + 1</button>
            <hr/>
            <h2>{newValue}</h2>
        </div>
    )
}

Analytical chestnut

When clicked 5 times, update numValue, in page newValueThe value of is always displayed as 0. Why?

Because I’m here useMemoThe monitoring record is countValue of when countWhen the value changes, the newValueIt will be recalculated in, although you clicked the update 5 times num, the page is not updated, but it has been cached. When you click Update countWhen, it calculatesThe value of count + 1 and the value of num cache, the final result is 5.

The calculation consumption is reduced.

useCallback Improve performance optimization

definition

useCallbackIt can be said that useMemoGrammar sugar, can you use ituseCallbackImplemented, can be useduseMemo, commonly used to optimize the performance of react.

useCallbackParameters:

  • callbackIs a function used to process logic
  • array controluseCallbackRe execute the array of ⾏,When array changesWill be re executeduseCallback

use

Its use and useMemoIt’s the same, just useCallbackFunction returned.

import { useState, useCallback} from 'react';


export default () => {
    const  [count, setCount] = useState(0)
    const [num, setNum] = useState(0)
    const newValue = useCallback(()=>{
        Console.log (` count value is ${count} `)
        Console.log (` num value is ${num} `)
        return count+num
    },[count])
    return(
        <div>
            <h1>{count}</h1> 
            <button onClick={()=>{setCount(count+1)}}>count + 1</button>
            <hr/>
            <h1>{num}</h1> 
            <button onClick={()=>{setNum(num+1)}}>Num + 1</button>
            <hr/>
            {/ * value returned by calling usecallback * /}
            <h2>{newValue()}</h2>
        </div>
    )
}

Summary

useMemoand useCallbackThe functions are similar, which are to improve performance optimization.

Which way to best practice remains to be explored.

Readers are welcome to communicate with me.

<br/>

Online pairuseMemoand useCallbackWhat do you think?

useCallbackIf it is used in functional components, it should indeed be used as a best practice, but its purpose is not only to cache the callback function with unchanged dependency (similar to usememo), but also to ensure that the callback function is always the latest instance when the dependency changes, so as not to cause some unexpected problems, I feel that the latter is the starting point for using usecallback, not caching. Because you think, even if usecallback is not used, assuming that the callback function does not have any dependency state, can I directly declare this function outside the component? Isn’t it freer for me to use ref directly< br/><br/>

useMemoThe name itself is associated with the cache. In essence, it is to solve a problem. Do not directly create objects or methods in render, because each time the component is rendered, it will be created (such as style or some constant states), resulting in unnecessary waste of resources. Ideally, if there is a dependency, it should be recreated only when the dependency changes. If there is no dependency, it should be created only once. On the surface, if usememo is used for all States, there must be no problem, but you still need to analyze this problem from the cost of caching. If the cost of using usememo to cache a state is greater than its advantages, is it counterproductive?

Everyone is rightuseMemoand useCallbackIf you have any comments, please comment below or add me to discuss.

useImperativeHandle

definition

useImperativeHandleCan let you userefCustomize the instance value exposed to the parent component when. In most cases, use should be avoided refSuch imperative code. useImperativeHandleShould be with forwardRefUse together.

useImperativeHandle effect:

Child components can be exposed to parent component instances for use

Format: useimperativehandle (ref, () = > {}, [])

  • Parameter 1: instances exposed by child components to parent components
  • Parameter 2: function, passed parent component, actionable instance and method
  • Parameter 3: listening status, update status
import {useState,useImperativeHandle, forwardRef,useRef} from 'react';


const Son = forwardRef( (props,ref) => {
    const inputRef = useRef(0)
    const domRef = useRef()
    Const [state, setstate] = usestate ('Wait ')
    useImperativeHandle(ref,()=>({
        focus:() => {inputRef.current.focus()},
        domRef
    }))
    return (
        <div>
            <h1>{state}</h1>
            <hr/>
            <input type="text" ref={inputRef}/>
            < H2 ref = {domref} > test ----------- useimperativehandle</h2>
        </div>
    )
})


export default () => {
    const refFather = useRef(0)
    return (
        <div>
            <h1>Parent component</h1>
            <Son ref={refFather} />
            < button onclick = {() = > {reffather. Current. Focus ()}} > get sub component instance ------ get input focus < / button >
            < button onclick = {() = > {console. Log (reffather. Current. Domref. Current. InnerHTML)} >
        </div>
    )
}

useReducer

definition

It isuseStateAlternatives. It receives a shape such as(state, action) => newStateofreducer, and returns the current state And its supportingdispatchmethod.

If familiar ReduxIf you use it, use it useReducerI’m familiar with the road. It’s time to start.

useReducerImplement an adder and subtractor

import {useReducer} from 'react';


export default () => {
    const [state, dispatch] = useReducer((state,action)=> {
        switch (action.type){
            case 'addNum':
                return {
                    num:state.num+1
                }
            case 'subtractNum':
                return {
                    num:state.num-1
                }
        }
            
    },{
        num:0
    })
    return (
        <div>
            <h2>{state.num}</h2>
            < button onclick = {() = > {dispatch ({type: 'addnum'})}} > Add num < / button >
            < button onclick = {() = > {dispatch ({type: 'subtractnum'})}} > minus num < / button >
        </div>
    )
}

epilogue

❤️ Follow + like + collect + comment + forward ❤️, Original is not easy, encourage the author to create better articles

If it feels good,Give me something to watch / like / pay attention toOfficial account: "front end self learning community", it’s better to have your attention

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]