Why need to use hooks?

There are 3 drawbacks by using class component in React:

  1. Big component is hard to split or restructure
  2. Logic is scattered in methods which can lead to redundant logic.
  3. Coding model is complicated, such as render, props, etc.

To simplify coding in React, Hooks is designed, used in pure methods, which don't need class to complete a component. Notice, Hooks don't work inside classes!

Build-in Hooks

There are 4 commonly used hooks: useState(), useContext(), useReducer() and useEffect().

useState() is used when you need to manipulate state in a function.

import React, {useState} from "react"

export default function Fruit(){
    //declare hookks, initial value for fruit is banana, setFruit is used to handle changes.
    const [fruit, setFruit]=useState("banana");
    
    function handleChange(){
        return setFruit("orange");
    }
    return <button onclick={handleChange}>{fruit}</button>
    // can directly use fruit
}

useEffect() lets you perform side effects. general ways to use it is to request data. Effects are run after updating the DOM. Unlike componentDidMount, effects don't block the browser from updating the screen. Major effects don't need to happen synchronously, so it makes the app more responsive.

function User(Id){
    const [loading, setLoading]=useState(true);
    const [user, setUser]=useState({});
    
    useEffect(()=>{
        setLoading(true);
        fetch(`https://sample/${Id}`)
        .then(response=>response.json())
        .then(data=>{
            setUser(data);
            setLoading(false);
        });
    },[Id]);
    if(loading===true){
        return <p>Loading...</p>
    }
    
    return(
        <div>
          <p> User name: {user.Name}</p>
        </div>
    )
}

Notice: for needs of executing effect each time there is a update, can delete the second parameter in useEffect(); for needs of render once, can make the second parameter as [], so there is no change for a [], it will only executed once.