Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

React Hooks を安全に使う

React Hooks を安全に使う

kobayang

May 27, 2019
Tweet

More Decks by kobayang

Other Decks in Technology

Transcript

  1. ©2018 Wantedly, Inc. e.g. useRect: divͷେ͖͞Λऔಘ͢ΔCustom Hooks export const useRect

    = () => { const [rect, setRect] = useState<ClientRect | DOMRect>(); const ref = useRef<HTMLDivElement | null>(null); const resize = () => { const target = ref.current; if (target) { const rect = target.getBoundingClientRect(); setRect(rect); } }; useEffect(() => resize(), [resize]); return { ref, rect }; }
  2. ©2018 Wantedly, Inc. e.g. useRect: divͷେ͖͞Λऔಘ͢ΔCustom Hooks export const useRect

    = () => { const [rect, setRect] = useState<ClientRect | DOMRect>(); const ref = useRef<HTMLDivElement | null>(null); const resize = () => { const target = ref.current; if (target) { const rect = target.getBoundingClientRect(); setRect(rect); } }; useEffect(() => resize(), [resize]); return { ref, rect }; } resizeؔ਺͸ඳը͝ͱʹੜ੒͞Εͯ͠·͏
  3. ©2018 Wantedly, Inc. e.g. useRect: divͷେ͖͞Λऔಘ͢ΔCustom Hooks export const useRect

    = () => { const [rect, setRect] = useState<ClientRect | DOMRect>(); const ref = useRef<HTMLDivElement | null>(null); const resize = useCallback(() => { const target = ref.current; if (target) { const rect = target.getBoundingClientRect(); setRect(rect); } }, []); useEffect(() => resize(), [resize]); return { ref, rect }; } useCallbackͰؔ਺ΛϝϞԽ͢Δ
  4. ©2018 Wantedly, Inc. e.g. counter const App: React.FC = ()

    => { const [count, setCount] = useState(0); const addCount = useCallback(() => { setCount(count + 1); }, []); return ( <div> <button onClick={() => addCount()}>Add Count</button> <p>count: {count}</p> </div> ); };
  5. ©2018 Wantedly, Inc. e.g. counter const App: React.FC = ()

    => { const [count, setCount] = useState(0); const addCount = useCallback(() => { setCount(count + 1); }, []); return ( <div> <button onClick={() => addCount()}>Add Count</button> <p>count: {count}</p> </div> ); }; count ͷࢀর͕ݹ͍
  6. ©2018 Wantedly, Inc. e.g. counter const App: React.FC = ()

    => { const [count, setCount] = useState(0); const addCount = useCallback(() => { setCount(count + 1); }, [count]); return ( <div> <button onClick={() => addCount()}>Add Count</button> <p>count: {count}</p> </div> ); }; count ΛୈೋҾ਺ʹ௥Ճ͢Δ
  7. ©2018 Wantedly, Inc. disableʹ͢Δ৔߹͸ඞͣཧ༝Λॻ͘ useEffect(() => { // apolloClient ͸ඳը͝ͱʹੜ੒͞ΕͯΔͨΊઃఆ͠ͳ͍

    // eslint-disable-next-line react-hooks/exhaustive-deps }, [paramId]); useEffect(() => { // mount࣌ʹҰ౓͚࣮ͩߦ͍ͨ͠ͷͰ deps Λۭʹ͍ͯ͠·͢ɻ // eslint-disable-next-line react-hooks/exhaustive-deps }, []);
  8. ©2018 Wantedly, Inc. exhaustive-deps Ͱ͸νΣοΫͰ͖ͳ͍έʔε const handleResize = debounce(resize, 16);

    useEffect(() => { handleResize(); window.addEventListener("resize", handleResize); return () => { window.removeEventListener("resize", handleResize); }; }, [handleResize]); →ؒ઀తʹؔ਺͕มԽ͢Δ৔߹