useMemo和useCallback
2019-10-07 本文已影响0人
郁南
参考文章:链接
useMemo
import React, { useState, useMemo, useCallback, useEffect } from 'react';
export default function WithMemo() {
const [count, setCount] = useState(1);
const [val, setValue] = useState('');
/** 只有count变化,expensive函数才会执行 */
const expensive = useMemo(() => {
console.log('compute');
let sum = 0;
for (let i = 0; i < count * 100; i++) {
sum += i;
}
return sum;
}, [count]);
return (
<div>
<h4>
{count}-{expensive}
</h4>
{val}
<div>
<button onClick={() => setCount(count + 1)}>+c1</button>
<input value={val} onChange={event => setValue(event.target.value)} />
</div>
</div>
);
}
useCallback
import React, { useState, useMemo, useCallback, useEffect } from 'react';
function Child(props: any) {
console.log('Parent数据有变化都会进来');
const [count, setCount] = useState(() => props.callback());
useEffect(() => {
console.log('callback变化的时候才会再次执行setCount');
setCount(props.callback());
}, [props.callback]);
return <div>{count}</div>;
}
export default function Parent() {
const [count, setCount] = useState(1);
const [val, setVal] = useState('');
/** 类似于useMemo函数 */
const callback = useCallback(() => {
return count;
}, [count]);
return (
<div>
<h4>{count}</h4>
<h4>{val}</h4>
<Child callback={callback} />
<div>
<button onClick={() => setCount(count + 1)}>+</button>
<input value={val} onChange={event => setVal(event.target.value)} />
</div>
</div>
);
}