useCallback()
を利用するメリット
通常、Reactコンポーネント内で宣言したコールバック関数はrender毎に生成される
useCallback()
を使うと、、、
コールバック関数の再生成を抑止(不変値化)
クラスコンポーネントのbind()
と似た役割
useCallback()
の使い方
文法
useCallback(() => {}, [hoge]) // (コールバック関数, deps(再描画の条件))
子コンポーネントにpropsで関数を渡す場合に使用する
const handleClose = useCallback(() => {
setOpen(false)
}, [])
// 中略
<FormDialog
open={open}
handleClose={handleClose}
/>
setOpen
がuseState
由来の関数の場合は、Reactで同一性が保証されているためdeps
に含めなくても問題ない
https://ja.reactjs.org/docs/hooks-reference.html#usestate
クラスコンポーネントとの比較
this.handleClose = this.handleClose.bind(this)
// 中略
handleClose = () => {
this.setState({open: false})
}