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={increaseCounter2}>Coutner 2</Counter>
    </>
  )
}

export default App

但是大多数场景下,更新是没有必要的,我们可以借助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 = useCallback(() => {
    setCount1(count1 => count1 + 1)
  }, [])
  const increaseCounter2 = useCallback(() => {
    setCount2(count2 => count2 + 1)
  }, [])
  console.log(increaseCounter1)

  return (
    <>
      <Counter value={count1} onClick={increaseCounter1}>Counter 1</Counter>
      <Counter value={count2} onClick={increaseCounter2}>Coutner 2</Counter>
    </>
  )
}

export default App
posted @ 2020-03-20 21:39  剑仙6  阅读(741)  评论(0编辑  收藏  举报
欢迎访问个人网站www.qingchun.在线