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

複雑化したReact hookのデバッグとその対策

1coin
January 25, 2021

複雑化したReact hookのデバッグとその対策

1coin

January 25, 2021
Tweet

More Decks by 1coin

Other Decks in Technology

Transcript

  1. ϦχϡʔΞϧ࣌ͷۤ೰ • ϦϦʔεલʹΫϥείϯϙʔωϯτ͔Β ؔ਺ίϯϙʔωϯτ + Hookʹશॻ͖׵͑Λߦͬͨ • ॻ͖׵͑ͷཧ༝͸ɺcomponentDidUpdateͷ৚݅෼ذ͕ෳࡶԽͯ͠ ͍ͨΊɻHookͷuseEffectͰॲཧΛ෼཭͠ରࡦΛߦͬͨɻ •

    ಄Λ೰·ͤͨͷ͕ɺHookͷґଘ഑ྻͷ؅ཧɻಛʹuseEffect͸׳Ε ͕ඞཁͰɺແݶϧʔϓ͕ൃੜ͢ΔͳͲ໰୊͕ଟ͔ͬͨɻ • ౰࣌ɺσόοάํ๏΋৘ใΛݟ͚ͭΒΕͣۤ࿑ͨ͠ 4
  2. Hookͷґଘ഑ྻΛ͓͞Β͍ • ґଘ഑ྻ = Hookͷୈ2Ҿ਺ͷ഑ྻ • Hookͷൃಈʹ৚݅Λ͚ͭΔ͜ͱ͕Ͱ͖Δɻਖ਼͘͠ઃఆ͠ͳ͍ͱಈ͔ͳ͍ɾಈ͍ͯ͠·͏ const [count, setCount]

    = useState(0) // mount࣌ͷΈ࣮ߦ useEffect(() => { console.log("Mount:" + count) },[]) // []͸৚݅ͳ͠); // mount + count͕ߋ৽͞Εͨ࣌ʹ࣮ߦ useEffect(() => { console.log("Update:" + count) },[count]) // count͕มԽͨ࣌͠); 7
  3. Hookͷґଘ഑ྻΛ͓͞Β͍ • ಺෦ͰsetNumberͨ͠ΒͲ͏ͳΔͰ͠ΐ͏? • => countߋ৽ˠuseEffect→countߋ৽ˠuseEffect→... => ແݶϧʔϓ͕ൃੜ const [count,

    setCount] = useState(0) // mount࣌ͷΈ࣮ߦ useEffect(() => { console.log("Mount:" + count) },[]) // []͸৚݅ͳ͠); // mount + count͕ߋ৽͞Εͨ࣌ʹ࣮ߦ useEffect(() => { console.log("Update:" + count) // ௥Ճ setCount(count+ 1) },[count]) // ґଘ഑ྻ); 8
  4. σόοάʹศརͳϥΠϒϥϦ • simbathesailor/use-what-changed2 • ίϯιʔϧʹHookมԽΛग़ྗ • custom Hook/babel plugin •

    kentcdodds/stop-runaway-react-effects3 • ແݶϧʔϓൃੜ࣌ɺΞϓϦΛఀࢭ͠ίϯιʔϧʹܯࠂΛग़ྗ 3 https://github.com/kentcdodds/stop-runaway-react-effects 2 https://github.com/simbathesailor/use-what-changed 12
  5. use-what-changed:Πϯετʔϧํ๏ɹ • bable.config.json { "presets": [ "react-app" ], "plugins": [

    [ "@simbathesailor/babel-plugin-use-what-changed", { "active": true } ] ] } 15
  6. use-what-changed:࢖͍ํͱग़ྗ ؂ࢹ͍ͨ͠Hook্෦ʹuwc-debugͱίϝϯτ͢Δ͚ͩ uwc-debug-belowͩͱҎ߱ͷHook͢΂ͯΛର৅ʹͰ͖Δ const [a, setA] = useState("React Night"); const

    [b, setB] = useState(1); // uwc-debug useEffect(() => { // do something }, [a, b]); <button onClick={() => { setB((b) => b + 1); }} > 16
  7. HookංେԽ΁ͷରࡦ 1. react-hooks/exhaustive-depsLint͸warnͰઃఆ͠ɺFix/disable͢Δ͔͸దٓ൑அɻ 2. ίϯϙʔωϯτ͔ΒϩδοΫΛ෼཭ • UIʹґଘ͠ͳ͍΋ͷ͸ɺίϯϙʔωϯτ֎ʹ • ൚༻త →

    ผϞδϡʔϧ / ίϯϙʔωϯτґଘ → ίϯϙʔωϯτ಺ 3. ReduxͳΒ͹ɺre-ducks4ͷߟ͑ʹج͖ͮɺoperations/selectorsʹ෼཭ 4. custom HookΛੵۃతʹ࡞੒ Fat → slimʹͳͬͨίϯϙʔωϯτ෼ׂͰ੹຿Λ੔ཧ͍ͯ͘͠ 4 https://github.com/alexnm/re-ducks 19
  8. ࢀߟࢿྉ • useEffect׬શΨΠυ — Overreacted1 • Debug your Reactjs Hooks

    with ease !! | by Anil Chaudhary | Medium • ҆શʹ React Hooks Λ࢖༻͢Δ - Qiita • ϑοΫʹؔ͢ΔΑ͋͘Δ࣭໰ – React 1 https://iqkui.com/ja/a-complete-guide-to-useeffect/ 22