Upgrade to Pro — share decks privately, control downloads, hide ads and more …

useRefについて調べてみた

Kazuki Shibata
September 04, 2019

 useRefについて調べてみた

2019.09.04 React LT会の発表資料です。
https://informetis.connpass.com/event/142183/

Kazuki Shibata

September 04, 2019
Tweet

More Decks by Kazuki Shibata

Other Decks in Technology

Transcript

  1. DOMͷࢀরʹ࢖͑ΔʢެࣜྫΑΓʣ function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick

    = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
  2. useRefͷ࣮૷ function mountRef<T>(initialValue: T): {current: T} { const hook =

    mountWorkInProgressHook(); const ref = {current: initialValue}; if (__DEV__) { Object.seal(ref); } hook.memoizedState = ref; return ref; } function updateRef<T>(initialValue: T): {current: T} { const hook = updateWorkInProgressHook(); return hook.memoizedState; } ϝϞϦ্ͷ஋Λຖճฦ͚ͩ͢ ϝϞϦ্ͰΦϒδΣΫτΛอ࣋ currentϓϩύςΟʹ஋Λอ࣋
  3. inputཁૉͷྫ: useState function TextInput() { const [ text, setText ]

    = useState(‘’); const onChange = useCallback(e => { setText(e.target.value); }; return ( <input onChange={onChange} type="text" /> ); } ςΩετΛมߋ͢Δͨͼʹඳը͞ΕΔ
  4. inputཁૉͷྫ: useRefʢcurrent௚ࢦఆʣ function TextInput() { const { current } =

    useRef(null); const onChange = useCallback(e => { current = e.target.value; }); return ( <input onChange={onChange} type="text" /> ); } ςΩετΛมߋͯ͠΋࠶ඳը͞Εͳ͍
  5. inputཁૉͷྫ: useRefʢDOMࢀরʣ function TextInput() { const inputEl = useRef(null); return

    ( <input ref={inputEl} type="text" /> ); } ΋ͪΖΜ͜ͷํ๏΋࠶ඳը͞Εͳ͍
  6. useRefͷ࣮૷ function mountRef<T>(initialValue: T): {current: T} { const hook =

    mountWorkInProgressHook(); const ref = {current: initialValue}; if (__DEV__) { Object.seal(ref); } hook.memoizedState = ref; return ref; } function updateRef<T>(initialValue: T): {current: T} { const hook = updateWorkInProgressHook(); return hook.memoizedState; } ϝϞϦ্ͷ஋Λຖճฦ͚ͩ͢ ϝϞϦ্ͰΦϒδΣΫτΛอ࣋ currentϓϩύςΟʹ஋Λอ࣋