|
| 1 | +## useCallback |
| 2 | + |
| 3 | +```tsx |
| 4 | +import { memo, useState } from 'react' |
| 5 | +import './App.css' |
| 6 | + |
| 7 | +const Child = memo(() => { |
| 8 | + console.log('Child render') |
| 9 | + return <div>Child</div> |
| 10 | +}) |
| 11 | + |
| 12 | +function App() { |
| 13 | + const [count, setCount] = useState(0); |
| 14 | + |
| 15 | + return ( |
| 16 | + <> |
| 17 | + <button onClick={() => setCount((count) => count + 1)}>{count}</button> |
| 18 | + <Child /> |
| 19 | + </> |
| 20 | + ) |
| 21 | +} |
| 22 | + |
| 23 | +export default App |
| 24 | +``` |
| 25 | +> meno允许我们将组件包裹起来,只要Props不变,就不会重新渲染 |
| 26 | +
|
| 27 | +- 但是如果我们传递的是一个函数,那么每次父组件更新,都会重新渲染子组件,因为每次父组件更新,都会重新创建一个新的fn函数,这样就会导致子组件重新渲染 |
| 28 | +```tsx |
| 29 | +import { memo, useState } from 'react' |
| 30 | +import './App.css' |
| 31 | + |
| 32 | +interface IProps { |
| 33 | + fn: () => void |
| 34 | +} |
| 35 | +const Child = memo((props: IProps) => { |
| 36 | + const { fn } = props |
| 37 | + console.log('Child render', fn) |
| 38 | + return <div>Child</div> |
| 39 | +}) |
| 40 | + |
| 41 | +function App() { |
| 42 | + const [count, setCount] = useState(0); |
| 43 | + const fn = () => { |
| 44 | + console.log('fn') |
| 45 | + } |
| 46 | + |
| 47 | + return ( |
| 48 | + <> |
| 49 | + <button onClick={() => setCount((count) => count + 1)}>{count}</button> |
| 50 | + <Child fn={fn} /> |
| 51 | + </> |
| 52 | + ) |
| 53 | +} |
| 54 | + |
| 55 | +export default App |
| 56 | +``` |
| 57 | +- 这个时候可以使用useCallback来解决这个问题 |
| 58 | + |
| 59 | +```tsx |
| 60 | +import { memo, useState, useCallback } from 'react' |
| 61 | +import './App.css' |
| 62 | + |
| 63 | +interface IProps { |
| 64 | + fn: () => void |
| 65 | +} |
| 66 | + |
| 67 | +const Child = memo((props: IProps) => { |
| 68 | + const {fn} = props |
| 69 | + console.log('Child render', fn) |
| 70 | + return <div>Child</div> |
| 71 | +}) |
| 72 | + |
| 73 | +function App() { |
| 74 | + const [count, setCount] = useState(0); |
| 75 | + const fn = useCallback(() => { |
| 76 | + console.log('fn') |
| 77 | + }, []); |
| 78 | + |
| 79 | + return ( |
| 80 | + <> |
| 81 | + <button onClick={() => setCount((count) => count + 1)}>{count}</button> |
| 82 | + <Child fn={fn}/> |
| 83 | + </> |
| 84 | + ) |
| 85 | +} |
| 86 | + |
| 87 | +export default App |
| 88 | +``` |
0 commit comments