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

useRefについて調べてみた

 useRefについて調べてみた

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

B22ff27b7826e3299c8dba2e99f2aef8?s=128

Kazuki Shibata

September 04, 2019
Tweet

Transcript

  1. useRefʹ͍ͭͯௐ΂ͯΈͨ @shibe97 2019.9.4 React LTձ

  2. ࣲా ࿨ف ΢ΥϯλגࣜձࣾͰmicroCMSͱ͍͏ϔουϨεCMSΛ ࡞͍ͬͯ·͢ɻ ීஈ͸React࢖͍Ͱɺ࠷ۙVue΋ͪΐͬͱ৮Γ·͢ɻ @shibe97

  3. None
  4. ೖྗϑΥʔϜͱAPIΛඵͰ࡞੒Ͱ͖ΔαʔϏε

  5. React Hooksͱ͸ • React 16.8͔Β௥Ճ͞Εͨػೳ • Functional ComponentʹClass Componentͱಉ༷ͷॲཧ͕
 Ͱ͖ΔΑ͏ʹ௥Ճ͞Εͨ

    • state΍ϥΠϑαΠΫϧ૬౰ͷ΋ͷ
  6. useRefͱ͸ • DOMͷࢀরʹ࢖͑Δ • ࠶ඳըͤ͞ͳ͍ม਺؅ཧ͕Ͱ͖Δ

  7. 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> </> ); }
  8. ࠶ඳըͤ͞ͳ͍ม਺؅ཧ͕Ͱ͖Δ • refΦϒδΣΫτ͸஋ΛcurrentϓϩύςΟʹอ࣋͢Δ • ࠶ඳը࣌΋ɺຖճಉ͡refΦϒδΣΫτΛฦ͢ • currentʹ௚઀୅ೖͯ͠΋࠶ඳը͸͞Εͳ͍ { current: initialValue

    }
  9. 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ϓϩύςΟʹ஋Λอ࣋
  10. ͜ͷ࢓૊ΈΛར༻Ͱ͖ΔྫͬͯͳΜͩΖ͏

  11. DOMͩʂ

  12. inputཁૉͷྫ: useState function TextInput() { const [ text, setText ]

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

    useRef(null); const onChange = useCallback(e => { current = e.target.value; }); return ( <input onChange={onChange} type="text" /> ); } ςΩετΛมߋͯ͠΋࠶ඳը͞Εͳ͍
  14. ͋ΕɺͰ΋͜Εͬͯɾɾɾ

  15. inputཁૉͷྫ: useRefʢDOMࢀরʣ function TextInput() { const inputEl = useRef(null); return

    ( <input ref={inputEl} type="text" /> ); } ΋ͪΖΜ͜ͷํ๏΋࠶ඳը͞Εͳ͍
  16. ·ͱΊ • useRef͸஋Λอ࣋Ͱ͖Δ্ʹɺมߋͯ͠΋࠶ඳը͞Εͳ͍ • inputཁૉʹ͸useStateΑΓuseRefͷํ͕ύϑΥʔϚϯε͸ྑ͍ • ΋ͪΖΜControlled Componentʹ͍ͨ͠৔߹͸useStateʹ͢Δ ඞཁ͋Γ

  17. ͓·͚

  18. useRef͸ΦϒδΣΫτΛࢀর͍ͯ͠Δ͔Β ಺෦ϓϩύςΟมߋͨ͠ͱ͜ΖͰ࠶ඳը͞Εͳ͍ΜͩΖ͏

  19. Α͠ɺLTωλ͸͜ΕͰ͍͜͏ʂ

  20. 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ϓϩύςΟʹ஋Λอ࣋
  21. ·ͬͨؔ͘܎ͳ͔ͬͨ

  22. Thanks :) @shibe97