When the dogs in the village barked, the other dogs followed, but they did not know why.

React Hook

React Hook? React Hook is a new feature in Update 16.8 that allows you to use state and other React features without having to write classes.

Why react Hook

The React component has a class component, a function component, a stateless component, and a function component. The function component has higher performance than the class component.


Why use hook


  • This points to the problem
  • State logic reuse
  • Separation of concerns

React Hook

StateHook

StateHook provides the ability to use state in functional components

import React,{useState} from 'react';
function Count() {
    const [count,setCount] = useState(0);
    const [num,setNum] = useState(10);
    return (
        <div>
                <div>
                    <button onClick={()=>setCount(count+1)}>{count}</button>
                </div>
                <div>
                    <button onClick={()=>setCount(num+2)}>{num}</button>
                </div>
            </div>
    )
}
Copy the code
This is a simple example of using useState to return an array containing two items. The first item is a value that can be understood as a property defined in state when using the class component, and the second item is a function that changes the value, which can be understood as a layer 2 encapsulation of setState.


Note:


  • The number and sequence of useState calls cannot be dynamically changed
  • UseState takes either a parameter as the default value or a receiving function, depending on the first render call to useState. If it is a function, it is called only once and the value returned is the default value

How many questions might you have?

  • 1. How does stateHook know to return count for this component and not for some other component
  • 2. How does stateHook know if it is returning the value of count or num
UseState will only return the count of the component, and my guess is based on the execution context.


The first call returns the value of count and the second call returns the value of num.


EffectHook

Function components do not support lifecycle functions, so EffectHook provides one. Just to clarify
UseEffect takes a function and an array as arguments and will not be called again unless each item in the array is unchanged.


Therefore, there are several situations:

  • 1. Passing only the first argument, this function is called every time the page is rendered, like componentDidMount and componentDidUpdate

    function App(props) { const [count,setCount] = useState(0); UseEffect (()=>{// Console. log('mount and update') is called after each rendering; }); . }

  • This function will only be called once when the page component is rendered to the page, like componentDidMount

    function App(props) { const [count,setCount] = useState(0); UseEffect (()=>{// Like componentDidMount only calls console.log('mount and update') once; } []); . }

  • (2) componentWillUnmount (); (3) componentWillUnmount (); The second is called before the next component starts rendering

    function App(props) { const [count,setCount] = useState(0); useEffect(()=>{ return ()=>{ console.log('mount and update'); }; }); . }

  • 4. If the second argument is not an empty array, it will not fire if each item in the array does not change pairs

    function App(props) { const [count,setCount] = useState(0); useEffect(()=>{ console.log('mount and update'); },[count===4]); . }

ContextHook

ContextHook provides the ability for function components to use context

            const CountText = createContext(1);
            function App(props) {
              const [count,setCount] = useState(0);
              return (
              	...
                <Counttext.Provider value={{count}}>
                       <Tab/>
                 </Counttext.Provider>
                ...
              )
            }
            function Tab(props) { 
            	const context = useContext(CountText);
                return (
                	<div>
                   		 {context.count}
                       </div>
                );
            }
        

MemoHook&&CallbackHook

MemoHook and CallbackHook are both means of performance optimization, similar to shouldComponentUpdate for class components.

function App() { const [count,setCount] = useState(0); const double = useMemo(()=>{ return count * 2; },[count===4]); return ( &lt; div&gt; {double} &lt; /div&gt; ) ; } </pre> </code> the second parameter is used in the same way as the second parameter of useEffect. Remember to useMemo when useMemo returns a function, CallbackHook can be used, CallHook can be used as a variant of MemoHookCopy the code

RefHook

RefHook provides the ability for function components to manipulate DOM nodes. Refhooks are commonly used in two scenarios: manipulating DOM nodes or components and sharing data across cycles.

  • 1. Operate DOM nodes

                function App(props) {
                    const [count,setCount] = useState(0);
                    const ref = useRef();
                    const callback = useCallback(function() {
                    	setCount(count=>count+1);
                    })
                    useEffect(()=>{
                    	ref.current.addEventListener('click',callback,false);
                        return ()=>{
                        ref.current.removeEventListener('click',callback,false);
                        };
                    },[]);
                    return ( <div>
                    	       <button ref={ref}>
                                </button>
                              </div>)
                }
                

  • 2. Sharing data across cycles (bad example)

                function App(props) {
                    let it = useRef(); 
    				const [count,setCount] = useState(()=>0);
    
    useEffect(()=>{ it.current = 4; window.setInterval(()=>{ setCount(count=>{ return count+1; })}, 1000); },[it]); console.log(it.current); //undefined 4 4 4 4 ... } </pre> </code> <div>Copy the code

    So in this case, if the data is shared using state, the data will be re-rendered whenever it changes, so use non-state and RefHook. Refhooks can share data across cycles

</ul>
Copy the code

Customize the Hook

Custom Hooks are like normal functions, which return JSX values as well as other types of values
function useCount() {
    const [count,setCount] = useState(()=>0);
    
    const ref = useRef(); 
    useEffect(()=>{
        ref.current = window.setInterval(()=>{
            setCount(count=>{
                if(count+1===10) {
                    window.clearInterval(ref.current);
                }
                return count+1;
            })
           
        },1000);
    },[]);
    return (
        <button ref={ref}>
            {count}
        </button>
   );
}
function App(props) {
 
    const ele = useCount();
    return ele;
}
Copy the code

Hook usage rules

  • 1. Hook only at the top level
  • 2. Only use hooks in function components or custom hooks