useMemo 是一個提高網頁效能的HOOK
它是利用js的緩存技術(Memoization)
它跟useEffect一樣有2個參數
useMemo{()=>{},[]}
而且執行順序useMemo會先被執行
import React, {useState,useEffect,useMemo} from 'react';
const Test1 = (props) => {
return(
<div>Test1</div>
);
}
export default function App(props) {
const [count, setCount] = useState(0);
useEffect(()=>{
console.log("useEffect");
});
useMemo(()=>{
console.log("useMemo");
});
return (
<div>
<Test1 />
<p>count:{count}</p>
<button onClick={(e) => { setCount( count+1 ) }}>ADD</button>
</div>
)
}
怎麼使用?
import React, {useState,useMemo} from 'react';
const Test1 = (props) => {
return(
<div>Test1</div>
);
}
export default function App(props) {
const [count, setCount] = useState(0);
let umemo = useMemo(()=>{
return count;
});
return (
<div>
<Test1 />
<p>count:{count}</p>
<p>usememo-count:{umemo}</p>
<button onClick={(e) => { setCount( count+1 ) }}>ADD</button>
</div>
)
}
第二個參數怎麼使用
import React, {useState,useMemo} from 'react';
const Test1 = (props) => {
return(
<div>Test1</div>
);
}
export default function App(props) {
const [count, setCount] = useState(0);
const [num, setNum] = useState(0);
let umemo = useMemo(()=>{
return {count,num};
},[num]);
return (
<div>
<Test1 />
<p>count:{count}</p>
<p>num:{num}</p>
<p>usememo-count:{umemo.count}</p>
<p>usememo-num:{umemo.num}</p>
<button onClick={(e) => { setCount( count+1 );console.log("count"+count); }}>ADD-count</button>
<button onClick={(e) => { setNum( num+1 );console.log("num"+num); }}>ADD-num</button>
</div>
)
}
測試點擊ADD-count 只有count會增加,其他都無反應
測試點擊ADD-num usememo-count會突然變9 跟count一樣數字
傳值到組件 再用useMemo來控制
import React, {useState,useMemo} from 'react';
const Test1 = ({nums,conus}) => {
let umemo = useMemo(()=>{
return {nums,conus};
},[nums]);
return(
<div>Test1-num{umemo.nums}-conut{umemo.conus}</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
const [num, setNum] = useState(0);
return (
<div>
<Test1 nums={num} conus={count} />
<p>count:{count}</p>
<p>num:{num}</p>
<button onClick={(e) => { setCount( count+1 );console.log("count"+count); }}>ADD-count</button>
<button onClick={(e) => { setNum( num+1 );console.log("num"+num); }}>ADD-num</button>
</div>
)
}