[react]--Basic use of Hooks - [Alley]

Posted by djpeterlewis on Sun, 16 Jun 2019 18:42:51 +0200

1. react-hooks concept


In React, everything is a component. Components in React are divided into class components and function components. In React, if you need to record the state of a component, it must be a class component.Can function components have the functionality of class components?At this point we need to use hooks.

Hook s gives our function components features similar to class components, which are new to React16.8 and allow you to use state and other React functions without writing classes

 

2. Why class components are required in React

1. The status of the current component needs to be recorded
2. Some life cycle functions that require components

 

3. Simple comparison between class components and Hooks

Class Components

 

import React from "react"

export default class App extends React.Component{
    constructor(){
        super();
        this.state = {
            count:0
        }
        this.handleClick = this.handleClick.bind(this);
    }
    render(){
        let {count} = this.state;
        return (
            <div>
                <h2>{count}</h2>
                <button onClick={this.handleClick}>modify</button>
            </div>
            )
    }
    handleClick(){
        this.setState({
            count:this.state.count+1
        })
    }
}

 

  hooks

import React,{useState} from "react";

export default ()=>{
    let [count,setCount] = useState(0);
    let handleAdd = ()=>setCount(count+1);
    return (
        <div>
            <h2>{count}</h2>
            <button onClick={handleAdd}>click</button>
        </div>
    )
}

Does Hooks feel much easier after comparing the two?So let's learn Hooks next

 

 

4. Basic Use of Hooks

 

1. Methods commonly used by Hooks
The three above methods, useState, useEffect, and useContext, are commonly used by hooks

 

  2,useState
UseState is a hook function that comes with react and is used to declare state variables. The useState function receives a parameter that is our initial state value and returns an array whose item [0] is

Item [1] is a method function that can change the current state value.

import React,{useState} from "react"

export default ()=>{
    let [count,setCount] = useState(0);
    let addCount = ()=>setCount(count+1);
    return (
        <div>
            <h2>{count}</h2>
            <button onClick={addCount}>click</button>
        </div>
    )
}

useState: Create a state of 0
count: represents the current state value, which is 0
setCount: Function to update status
AddCount = ()=>setCount (count+1); call setCount to modify state

 

2-1. What does useState return?

const [count,setCount] = useState(0);

const state = useState(0);
const count = state[0];
const setCount  = state[1]

Attention:

1. useState must be written at the beginning of the function and cannot be called inside loops or judgment statements, so that our ooks will be called in the same order each time they are rendered, because there is a key problem here: useState needs to match the right state by referencing the calling order of the first rendering, otherwise useStateTe will not return its state correctly for

2. We can use more than one function component

export default ()=>{
    let [count,setCount] = useState(0);
      let [count,setCount] = useState(0);
      let [count,setCount] = useState(0);
    
}

5. Basic use of useEffect
The stateful components that we write often have side effects, such as initiating ajax requests to get data, adding some monitored registrations and unregistering, manually modifying the dom, and so on.Previously, we wrote these side effects in the life cycle function hook, such as componentDidMount, componentDidUpdate, and componentWillUnmount.Now useEffect is equivalent to a collection of hooks that declare periodic functions.It's one to three.

            (useEffect = componentDidMount + componentDidUpdate+componentWillUnmount)

 

  5-1,useEffect
There are two parameters in useEffect, the first is a function and the second is a dependent data.The second parameter is used to decide whether to perform the operation inside or not, avoiding unnecessary performance penalties and skipping this execution as long as the value of the member in the second parameter has not changed.If an empty array [] is passed in, the effect will only execute during the components mount and unmount periods.

5-2, useEffect simulates componentDidMount && componentDidUpdate

import React,{useState,useEffect} from "react"

export default ()=>{
    let [title,setTitle] = useState(0);
    let updateTitle = ()=>setTitle(title+1);
    return (
        <div>
            <h2>{title}</h2>
            <button onClick={updateTitle}>click</button>
        </div>
    )
    
    //A parameter is a function every time mount perhaps update Will call the current function
    useEffect(()=>{
        document.title = `Page is ${count}`;
    })
    
}

  

5-3. How to execute in componentDidMount only

import React,{useState,useEffect} from "react"

export default ()=>{
    let [title,setTitle] = useState(0);
    let updateTitle = ()=>setTitle(title+1);
    return (
        <div>
            <h2>{title}</h2>
            <button onClick={updateTitle}>click</button>
        </div>
    )
    
    //Setting the second parameter to an empty array will only work on componentDidMount Medium Execution
    useEffect(()=>{
        document.title = `Page is ${count}`;
    },[])
    
}

5-2, useEffect simulation componentWillUnMount
The useEffect can also do some cleanup by having the function return a function, such as unsubscribe

useEffect = (()=>{
    return ()=>{
        //unmount Called here when
        document.removeEventListener();
    }
},[])

 

4. When does useEffect execute?(

It will be executed at component mount and unmount and each time it is re-rendered, that is, at componentDidMount, componentDidUpdate, componentWillUnmount

 

5. Benefits of hooks
Lifecycle-oriented programming becomes business logic-oriented programming

Topics: PHP React Programming