useCallback性能优化的点:
1.当需要将一个函数传递给子组件时, 最好使用useCallback进行优化, 将优化之后的函数, 传递给子组件。
useCallback拿到的是优化函数本身
app.js
import React, { memo, useState, useCallback, useRef } from 'react'
// props中的属性发生改变时, 组件本身就会被重新渲染
const HYHome = memo(function(props) {
const { increment } = props
console.log("HYHome被渲染")
return (
<div>
<button onClick={increment}>increment+1</button>
{/* 100个子组件 */}
</div>
)
})
const App = memo(function() {
const [count, setCount] = useState(0)
const [message, setMessage] = useState("hello")
// 闭包陷阱: useCallback
// const increment = useCallback(function foo() {
// console.log("increment")
// setCount(count+1)
// }, [count])
// 进一步的优化: 当count发生改变时, 也使用同一个函数(了解)
// 做法一: 将count依赖移除掉, 缺点: 闭包陷阱
// 做法二: useRef, 在组件多次渲染时, 返回的是同一个值
const countRef = useRef()
countRef.current = count
const increment = useCallback(function foo() {
console.log("increment")
setCount(countRef.current + 1)
}, [])
// 普通的函数
// const increment = () => {
// setCount(count+1)
// }
return (
<div>
<h2>计数: {count}</h2>
<button onClick={increment}>+1</button>
<HYHome increment={increment}/>
<h2>message:{message}</h2>
<button onClick={e => setMessage(Math.random())}>修改message</button>
</div>
)
})
export default App
useMeno性能优化的点:
useMeno拿到的是优化函数返回值
import React, { memo, useCallback } from 'react'
import { useMemo, useState } from 'react'
const HelloWorld = memo(function(props) {
console.log("HelloWorld被渲染~")
return <h2>Hello World</h2>
})
function calcNumTotal(num) {
// console.log("calcNumTotal的计算过程被调用~")
let total = 0
for (let i = 1; i <= num; i++) {
total += i
}
return total
}
const App = memo(() => {
const [count, setCount] = useState(0)
// const result = calcNumTotal(50)
// 1.不依赖任何的值, 进行计算
const result = useMemo(() => {
return calcNumTotal(50)
}, [])
// 2.依赖count
// const result = useMemo(() => {
// return calcNumTotal(count*2)
// }, [count])
// 3.useMemo和useCallback的对比
function fn() {}
// const increment = useCallback(fn, [])
// const increment2 = useMemo(() => fn, [])
// 4.使用useMemo对子组件渲染进行优化
// const info = { name: "why", age: 18 }
const info = useMemo(() => ({name: "why", age: 18}), [])
return (
<div>
<h2>计算结果: {result}</h2>
<h2>计数器: {count}</h2>
<button onClick={e => setCount(count+1)}>+1</button>
<HelloWorld result={result} info={info} />
</div>
)
})
export default App
网友评论