iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
Modern Web

白話JavaScript系列 第 26

Day26-useCallback

前言

在昨天我們學會使用memo去記憶我們的組件,達成避免re-render的狀態。

而我們今天會學習使用useCallback,來解決reference的問題。

useCallback

syntax

useCallback(() => {
    //block
},[dependency])

我們把昨天的code改成從外部定義好函式,再傳遞Props。

//App.js
import React, {useState,useCallback} from 'react'
import Button from '../Components/Button'
import Button2 from '../Components/Button2'
function App() {
  const [number, setNumber] = useState(0)
  const [number2 ,setNumber2] = useState(0)

  const increase = () => {
    setNumber(number + 1)
  }

  const increase2 = () => {
    setNumber2(number2 + 1)
  }
  return (
  <div>
    <Button setNumber={increase} value={number} />
    <Button2 setNumber2={increase2} value={number2}/>
  </div>
  )
}

export default App

//Button.js
import React, {memo} from 'react'

function Button({setNumber,value}) {
  console.log('button');

  return (
    <div>
      <button onClick={setNumber}>Click</button>
      {value}
    </div>

  )
}

export default memo(Button)

這時候我們會發現memo沒有辦法正確的比對參考,也就是函式被重新定義,但會變成不同記憶體位置。

  console.log({} === {}) //false

這時候我們就需要useCallback來記住記憶體位址。


//App.js

import React, {useState,useCallback} from 'react'
import Button from '../Components/Button'
import Button2 from '../Components/Button2'
function App() {
  const [number, setNumber] = useState(0)
  const [number2 ,setNumber2] = useState(0)

  const increase = useCallback(() => {
    setNumber(number + 1)
  },[number, setNumber ])

  const increase2 = useCallback(() => {
    setNumber2(number2 + 1)
  },[number2, setNumber2])
  return (
  <div>
    <Button setNumber={increase} value={number} />
    <Button2 setNumber2={increase2} value={number2}/>
  </div>
  )
}

export default App
// Button.js
import React, {memo} from 'react'

function Button({setNumber,value}) {
  console.log('button');

  return (
    <div>
      <button onClick={setNumber}>Click</button>
      {value}
    </div>

  )
}

export default memo(Button)

//Button2.js
import React, {memo, useState} from 'react'

function Button2({value, setNumber2}) {
  console.log('button2')
  return (
    <div>
      <button onClick={setNumber2}>Click</button>
      {value}
    </div>
  )
}

export default memo(Button2)

總結

  • memo 解決組件的記憶問題
  • useCallback 解決函式參考問題

上一篇
Day25-memo
下一篇
Day27-useMemo
系列文
白話JavaScript28

尚未有邦友留言

立即登入留言