0
0

More than 3 years have passed since last update.

useCallback 学習メモ

Last updated at Posted at 2020-12-27

useCallback()を利用するメリット

通常、Reactコンポーネント内で宣言したコールバック関数はrender毎に生成される

useCallback()を使うと、、、
コールバック関数の再生成を抑止(不変値化)
クラスコンポーネントのbind()と似た役割

useCallback()の使い方

文法

useCallback(() => {}, [hoge]) // (コールバック関数, deps(再描画の条件))

子コンポーネントにpropsで関数を渡す場合に使用する

const handleClose = useCallback(() => {
  setOpen(false)
}, [])
// 中略
<FormDialog
  open={open}
  handleClose={handleClose}
/>

setOpenuseState由来の関数の場合は、Reactで同一性が保証されているためdepsに含めなくても問題ない
https://ja.reactjs.org/docs/hooks-reference.html#usestate

クラスコンポーネントとの比較

this.handleClose = this.handleClose.bind(this)
// 中略
handleClose = () => {
  this.setState({open: false})
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0