其他分享
首页 > 其他分享> > useCallback()和useMemo()

useCallback()和useMemo()

作者:互联网

useMemo()和useCallback()都能够起到缓存的作用,只不过useMemo()针对于数据,useCallback()针对于函数

useMemo()

不使用useMemo()

当点击按钮时会改变value的值,同时也会一直执行console.log(1),即take函数一直在被调用

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

export default function UseMemo() {
  const [value, setvalue] = useState(0)
  const [count, setcount] = useState(1)
  const take = (count) => {
    console.log(1)
    return count * 3
  }
  const price = take(count)

  return (
    <div>
      <p>value:{value}   count:{price}</p>
      <button onClick={() => setvalue(value + 1)}>value+1</button>
    </div>
  )
}

使用useMemo

使用useMemo()包裹后,点击按钮不会引起take函数的执行,price的值始终都是从缓存里面拿到的,只有在后面的依赖里面添加了依赖,且依赖的值改变了,才会执行被包裹的代码,对性能有一定的提升

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

export default function UseMemo() {
  const [value, setvalue] = useState(0)
  const [count, setcount] = useState(1)
  const take = (count) => {
    console.log(1)
    return count * 3
  }
  const price = useMemo(() => {
    return take(count)
  }, [])
  return (
    <div>
      <p>value:{value}   count:{price}</p>
      <button onClick={() => setvalue(value + 1)}>value+1</button>
    </div>
  )
}

useCallback()

还没搞清楚,明天再继续

标签:count,const,useMemo,value,useCallback,useState,take
来源: https://www.cnblogs.com/oumannrinn/p/15902717.html