zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    JSP实现数据传递(web基础学习笔记三)
    Spring Boot 参数校验
    Spring AOP实践
    Spring AOP介绍
    2018年春节
    InnoDB索引
    Kafka基本知识回顾及复制
    Kakfa消息投递语义
    Kafka Consumer
    Kafka Producer Consumer
  • 原文地址:https://www.cnblogs.com/fightjianxian/p/12535074.html
Copyright © 2011-2022 走看看