Hook is a new feature React 16.8. It allows you to use the state as well as other React characteristics without writing class is.
Why use hooks?
- Logic state is difficult to reuse between components, may use to render props and high-end components, React need to provide a better way to share native state logic, Hook allows you to reuse the state without having to modify the structure of the logical components
- Complex components difficult to understand, Hook split portion interrelated components into smaller functions (such as setting data request or subscription)
- Incomprehensible class, including the elusive this
Use hooks Precautions
- Hook function can only be called in the outermost layer. Do not judge or subroutine call in the cycle conditions.
- Hook function can only be called in the assembly React. Do not call the other JavaScript function
A more detailed understanding may look official website .
1.useState use
//组件函数每次渲染都会被调用,每次执行都产生一个独立的闭包
import React,{useState,useEffect} from 'react';
import {render} from 'react-dom';
function Home(){
let [count1,setCount1] = useState(0);
function alertCount1(){
setTimeout(()=>{
alert(count1);
},3000);
}
return <div>
<p>count1: {count1}</p>
<button onClick={()=>setCount1(count1+1)}>count1+</button>
<button onClick={alertCount1}>alertCount1</button>
</div>
}
render(<Home />,window.root);
复制代码
2.useEffect use
- You do not need to clear the side effects
import React,{useState,useEffect} from 'react';
import {render} from 'react-dom';
function Home(){
let [count1,setCount1] = useState(0);
//如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
useEffect(()=>{
document.title = `这事第${count1}点击`;
})
return <div>
<p>count1: {count1}</p>
<button onClick={()=>setCount1(count1+1)}>count1+</button>
</div>
}
render(<Home />,window.root);
复制代码
- You need to clear side effects
Below each count1 plus 1 did not re-open a new timer so it will become increasingly faster, the need to clear this side effect. useEffect can return a function that will be unloaded in the assembly or re-re-render before execution.
The disadvantage is: when you click successively count1 plus, it will create a timer and Clear timer times. 11111 will not be printed.
import React,{useState,useEffect} from 'react';
import {render} from 'react-dom';
function Home(){
let [count1,setCount1] = useState(0);
//如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
useEffect(()=>{
let timer = setInterval(()=>{
console.log(11111);
},1000);
return ()=>{
clearInterval(timer);
}
})
return <div>
<p>count1: {count1}</p>
<button onClick={()=>setCount1(count1+1)}>count1+</button>
</div>
}
render(<Home />,window.root);
复制代码
The second parameter is useEffect dependency. If not dependent on any empty array parameters. So re-render time will not be executed useEffect function. At this point useEffect return function is performed only when the components to uninstall.
import React,{useState,useEffect} from 'react';
import {render} from 'react-dom';
function Count1(){
let [count1,setCount1] = useState(0);
//如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
useEffect(()=>{
let timer = setInterval(()=>{
console.log(11111);
},1000);
return ()=>{
clearInterval(timer);
}
},[])
return <div>
<p>count1: {count1}</p>
<button onClick={()=>setCount1(count1+1)}>count1+</button>
</div>
}
function Home(){
let [isShow,setIsShow] = useState(false);
//如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
let changeShow = ()=>{
setIsShow(!isShow);
}
return <div>
<button onClick={changeShow}>show</button>
{isShow&&<Count1></Count1>}
</div>
}
render(<Home />,window.root);
复制代码
3.useReducer use
- useState alternative. It takes a form such as (state, action) => newState the reducer, and returns the current state dispatch method and a companion
- In some scenarios, useReducer may be more appropriate than useState, for example, more complex logic state and comprising a plurality of sub-values, or the next state dependent on the previous state and the like
import React,{useState,useEffect,useReducer} from 'react';
import {render} from 'react-dom';
let initCount = 1;
function countRender(state,action){
switch(action.type){
case 'ADD':
return state+action.num;
case 'REDUCE':
return state-action.num;
default:
return state;
}
}
function Home(){
//这里熟悉redux用法的会有种亲切的赶脚
//useReducer 三个参数
//第一个reducer
//第二个initialState 第三个参数的时候直接作为初始化数据,有第三个参数的时候作为第三个参数函数的入参。
//第三个 initializer 惰性初始化函数返回初始化数据
let [count1,dispatch] = useReducer(countRender,initCount,(state)=>10+state);
return <div>
<p>count1: {count1}</p>
<button onClick={()=>dispatch({
type:"ADD",
num:3
})}>ADD</button>
<button onClick={()=>dispatch({
type:"REDUCE",
num:2
})}>REDUCE</button>
</div>
}
render(<Home />,window.root);
复制代码
4.useRef use
- Within the component uses
function Home(){
let myinput = useRef();
let submit = ()=>{
console.log(myinput.current.value);
}
return <div>
<input ref={myinput} type="text"/>
<button onClick={submit}>提交</button>
</div>
}
复制代码
- Sons assembly forward
import React,{useState,useEffect,useRef,useImperativeHandle} from 'react';
import {render} from 'react-dom';
function Home(){
let myinput1 = useRef();
let myinput2 = useRef();
let setInputs1 = ()=>{
myinput1.current.setValue("hello world");
myinput1.current.focus();
}
let setInputs2 = ()=>{
myinput2.current.value = "hello";
}
return <div>
<button onClick={setInputs1}>设置1</button>
<WithRefMyInputs1 ref={myinput1}/>
<button onClick={setInputs2}>设置2</button>
<WithRefMyInputs2 ref={myinput2}/>
</div>
}
function MyInputs1(props,ref){
let focusInput = useRef();
let valInput = useRef();
//自组件可以只暴露部分操作。
useImperativeHandle(ref,()=>({
focus(){
focusInput.current.focus();
},
setValue(val){
valInput.current.value = val;
}
}))
return <div>
<div>
获取焦点: <input ref={focusInput}/>
</div>
<div>
设置初始值: <input ref={valInput}/>
</div>
</div>
}
function MyInputs2(props,ref){
//子组件功能全部暴露
return <div>
<div>
设置初始值: <input ref={ref}/>
</div>
</div>
}
let WithRefMyInputs1 = React.forwardRef(MyInputs1);
let WithRefMyInputs2 = React.forwardRef(MyInputs2);
render(<Home />,window.root);
复制代码
5.useLayoutEffect use
- Its function signature is the same useEffect, but it will effect synchronous call after all of the DOM changes
- You can use it to read layout and synchronous triggering heavy DOM rendering,
- useLayoutEffect inside the browser before the implementation plan drawn updates will be synchronized refresh
- Whenever possible, use standard useEffect to avoid blocking the view update
import React,{useState,useEffect,useLayoutEffect} from 'react';
import {render} from 'react-dom';
function LayoutEffect() {
const [color, setColor] = useState('red');
//用法同useEffect 只是执行时机不同
useLayoutEffect(() => {
alert(color);
});
useEffect(() => {
console.log('color', color);
});
return (
<>
<div style={{ background: color }}>颜色</div>
<button onClick={() => setColor('red')}>红</button>
<button onClick={() => setColor('yellow')}>黄</button>
<button onClick={() => setColor('blue')}>蓝</button>
</>
);
}
render(<LayoutEffect />,window.root);
复制代码
6. Custom hook
- By custom Hook, logic components can be extracted in a function reusable.
//实现多个不同时间的倒计时功能
import React,{useState,useEffect,useLayoutEffect} from 'react';
import {render} from 'react-dom';
function formate(diffs){
let h = Math.floor(diffs/3600);
let m = Math.floor((diffs%3600)/60);
let s = diffs%60;
let zero =n=> n<10?'0'+n:n;
return `${zero(h)}:${zero(m)}:${zero(s)}`;
}
function diffTime(futureDate){
let futureTime = new Date(futureDate).valueOf();
let time = new Date().valueOf();
let diffs = (futureTime-time)/1000;
return diffs;
}
function useDiffTime(futureDate){
let [time,setTime] = useState(diffTime(futureDate));
useEffect(()=>{
setInterval(()=>{
setTime(time=>time-1);
},1000)
},[])
return time;
}
function Timer1(){
let time= useDiffTime(new Date().valueOf()+4200000);;
return <div>
倒计时{formate(time)}
</div>
}
function Timer2(){
let time= useDiffTime(new Date().valueOf()+3600000);;
return <div>
倒计时{formate(time)}
</div>
}
function Home(){
return <div>
<Timer1></Timer1>
<Timer2></Timer2>
</div>
}
render(<Home />,window.root);
复制代码
7. Performance Optimization
- When you call the update function State Hook and pass the current state, React skipped perform rendering and effect of sub-assemblies. (React use Object.is comparison algorithm to compare the state.) Simply are not giving concrete examples.
- Reduce rendering times.
1) The inline callback functions and dependency array as a parameter useCallback, it will return memoized version of the callback function, the callback function will only updated when a dependency change.
2) to create an array of functions and dependency as a parameter useMemo, it will only be recalculated memoized value only when a dependency change. This optimization helps to avoid high costs are calculated at each rendering
import React,{useState,useCallback,useMemo,memo} from 'react';
import {render} from 'react-dom';
function Child({onButtonClick,data}){
console.log('Child render');
return (
<button onClick={onButtonClick} >{data.number}</button>
)
}
let MemoChild = memo(Child);
function App(){
const [number,setNumber] = useState(0);
const [name,setName] = useState('zhufeng');
const addClick = useCallback(()=>setNumber(number+1),[number]);
const data = useMemo(()=>({number}),[number]);
console.log("App render");
return (
<div>
<input type="text" value={name} onChange={e=>setName(e.target.value)}/>
<MemoChild onButtonClick={addClick} data={data}/>
</div>
)
}
render(<App />,window.root);
复制代码
references:
Reproduced in: https: //juejin.im/post/5d009c145188254cf36f0d1c