Created
September 27, 2021 15:44
-
-
Save 0918nobita/d52c33d0fe39ebf28e37491bf92c2063 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { VFC, useMemo, useCallback, useState } from 'react'; | |
| export const App: VFC = () => { | |
| const [inputA, setInputA] = useState(''); | |
| const [inputB, setInputB] = useState(''); | |
| const onChangeA: React.ChangeEventHandler<HTMLInputElement> = | |
| // HTML 要素のコールバック関数が再描画のたびに生成し直しになるのを防ぐために useCallback を使う | |
| useCallback( | |
| (e) => { setInputA(e.target.value) }, | |
| [setInputA] | |
| ); | |
| const onChangeB: React.ChangeEventHandler<HTMLInputElement> = | |
| useCallback( | |
| (e) => { setInputB(e.target.value) }, | |
| [setInputB] | |
| ); | |
| const computed = useMemo(() => { | |
| // ここで、useState で管理している状態を用いた計算をする。 | |
| // inputA, inputB に依存していることを明記してメモ化しているので、 | |
| // inputA, inputB のいずれかに変更があったときに再計算される。 | |
| return `"${inputA}${inputB}"`; | |
| }, [inputA, inputB]); | |
| return ( | |
| <> | |
| <p>A: <input onChange={onChangeA}></input></p> | |
| <p>B: <input onChange={onChangeB}></input></p> | |
| <p>Computed: {computed}</p> | |
| </> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment