Detailed explanation of the usage of hooks of react

  • 2021-08-31 07:00:19
  • OfStack

Role of hooks

It changes the original development mode of React class and uses the function form instead. It changes the complex state operation form and makes it easier for programmers to use it; It changes the reusability of a state component and greatly increases the reusability of components.

useState


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

//  Usage status 
<p>You clicked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>click me</button>

useEffect

1 parameter


useEffect(()=>{
 console.log(" First render and update ")
})

Simulation:
componentDidMount componentDidUpdate

1 parameter with return


useEffect(()=>{
 console.log(" First render and update ")
return ()=>{console.log( First unload )}
})

Simulation:

componentDidMount componentDidUpdate

return

componetWillUnmount componentDidUpdate

The second parameter is an empty array, return


useEffect(()=>{
 console.log(" First render and update ")
return ()=>{console.log( First unload )}
},[])

componentDidMount and componetWillUnmount relative to life cycle

The second parameter is the specific value


useEffect(()=>{
 console.log(" First render and update ")
return ()=>{console.log( First unload )}
},[num])

Simulation

componentDidMount componentDidUpdate (update is only useful for num)

return

componetWillUnmount componentDidUpdate (update is only useful for num)

useRef


const inp = useRef(null)
<input ref={inp}>
// Call 
inp.current.value

Custom hook

Definition: const [size,setSize] = useState({height:xxx,width:xxx})

Handling:


const onResize = ()=>{setSize({width:xxx,height:xxx})}
 useEffect(()=>{
 Monitor events  window.addEventListener( " resize " ,onResize)
 return  Remove Listening ()=>window.removeEventListener( " resize " ,onResize)
 },[])

Return to return size

Use const size = useWinSize ()


Related articles: