useCallback优化React Hooks程序性能
useCallback
使用场景是:有一个父组件,其中包含子组件,子组件接收一个函数作为props;通常而言,如果父组件更新了,子组件也会执行更新;
import React, { useMemo, useCallback } from "react"
let Counter = ({ value, children, onClick }) => {
console.log('Render: ', children)
return (
<div onClick={onClick}>
{children}: {value}
</div>
)
}
Counter = React.memo(Counter)
const App = () => {
const [count1, setCount1] = React.useState(0)
const [count2, setCount2] = React.useState(0)
const increaseCounter1 = () => {
setCount1(count1 => count1 + 1)
}
const increaseCounter2 = () => {
setCount2(count2 => count2 + 1)
}
return (
<>
<Counter value={count1} onClick={increaseCounter1}>Counter 1</Counter>
<Counter value={count2} onClick