hooks之useCallback

import React, {
      useState,  useCallback } from 'react'


/**
 * useCallback解决的是传入子组件的函数参数过度变化导致子组件过度渲染的问题
 */
function UseMemoAPI() {
     
  const [count, setCount] = useState(0)

  // 假设什么都不依赖,子组件应该不渲染
  const click = useCallback(() => {
     
    console.log('click------------')
  }, [])

  return (
    <div>
      <button onClick={
     () => setCount(count + 1)}>Click ({
     count})</button>
      <Counter count={
     count}  click={
     click} />
    </div>
  )
}

/**
 * memo
 * 只要父组件的值不变化,子组件就没必要渲染,
 * 如果父组件传递函数情况下,可以useCallback来作为优化手段
 */

const Counter = memo(function (props) {
     
  console.log(1111)
  return (
    <h1 onClick={
     props.click}>{
     props.count}</h1>
  )
})

export default UseMemoAPI

你可能感兴趣的:(前端技术,react,hooks,reactjs)