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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM