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

React Hooks - Reacting to the hype

Felix Wu
January 22, 2019

React Hooks - Reacting to the hype

One of the biggest announcements and excitements of React Conf 2018 was the introduction of React Hooks. Hooks are a new feature that lets us use state and other React features without writing a class, essentially allowing us to reuse stateful logic without changing our component hierarchy as well as write cleaner and more maintainable React code. In this talk, I'll give you a brief overview of state and effect hooks and how to integrate them into your codeflow!

Felix Wu

January 22, 2019
Tweet

More Decks by Felix Wu

Other Decks in Technology

Transcript

  1. @flxwu React Hooks - Reacting to the hype REACT HOOKS

    reacting to the hype useEffect(() => { learnHooks() })
  2. @flxwu React Hooks - Reacting to the hype Component code

    overload Class Boilerplate 
 + Lifecycles
  3. @flxwu class GroupStatus extends Component { constructor(props) { super(props); this.state

    = {...} this.handleClick = this.handleClick.bind(this); } handleClick() { ... } render() { return ... } componentDidMount() { this.subscribeToStore(this.props.group.id); this.getGroupStatusFromAPI(this.props.group.id); this.startTimer(); } componentWillUnmount() { this.unsubscribeFromStore(this.props.group.id); this.cancelPendingRequest(); this.stopTimer(); } }
  4. @flxwu class GroupStatus extends Component { constructor(props) { super(props); this.state

    = {...} this.handleClick = this.handleClick.bind(this); } handleClick() { ... } render() { return ... } componentDidMount() { this.subscribeToStore(this.props.group.id); this.getGroupStatusFromAPI(this.props.group.id); this.startTimer(); } componentWillUnmount() { this.unsubscribeFromStore(this.props.group.id); this.cancelPendingRequest(); this.stopTimer(); } }
  5. @flxwu class GroupStatus extends Component { constructor(props) { super(props); this.state

    = {...} this.handleClick = this.handleClick.bind(this); } handleClick() { ... } render() { return ... } componentDidMount() { this.subscribeToStore(this.props.group.id); this.getGroupStatusFromAPI(this.props.group.id); this.startTimer(); } componentWillUnmount() { this.unsubscribeFromStore(this.props.group.id); this.cancelPendingRequest(); this.stopTimer(); } }
  6. @flxwu class GroupStatus extends Component { constructor(props) { super(props); this.state

    = {...} this.handleClick = this.handleClick.bind(this); } handleClick() { ... } render() { return ... } componentDidMount() { this.subscribeToStore(this.props.group.id); this.getGroupStatusFromAPI(this.props.group.id); this.startTimer(); } componentWillUnmount() { this.unsubscribeFromStore(this.props.group.id); this.cancelPendingRequest(); this.stopTimer(); } componentDidUpdate() { ... } }
  7. @flxwu React Hooks - Reacting to the hype Duplicate logic

    Huge components ⚛ Complex code Why?
  8. @flxwu React Hooks - Reacting to the hype Complex code

    mess of state and side-effects coherent code gets split
  9. @flxwu React Hooks - Reacting to the hype Complex code

    mess of state and side-effects coherent code gets split unrelated code ends up together
  10. @flxwu React Hooks - Reacting to the hype Duplicate logic

    Huge components ⚛ Complex code Why?
  11. @flxwu React Hooks - Reacting to the hype TIL;Hooks let

    you split one component into smaller functions based on what pieces are related
  12. @flxwu React Hooks - Reacting to the hype stateless components

    function Stateless(props) { // no state 
 return <div /> }
  13. @flxwu React Hooks - Reacting to the hype stateless components

    function Stateless(props) { // no state 
 return <div /> } ⬇
  14. @flxwu React Hooks - Reacting to the hype stateless components

    function Stateless(props) { // no state 
 return <div /> } ⬇ functional components
  15. @flxwu React Hooks - Reacting to the hype stateless components

    function Stateless(props) { // no state 
 return <div /> } ⬇ function WithState(props) { // use State&Lifecycles in Hooks here! return <div /> } functional components
  16. @flxwu React Hooks - Reacting to the hype “hooking into”

    React features ✅ no need to convert to class!
  17. @flxwu React Hooks - Reacting to the hype State Hook

    Built-in Hooks ⚓ hooking into React state: count [varName, setVarName] = useState(default) import React, { useState } from ‘react’;
  18. @flxwu React Hooks - Reacting to the hype State Hook

    Built-in Hooks count [varName, setVarName] = useState(default)
  19. @flxwu React Hooks - Reacting to the hype State Hook

    Built-in Hooks count [varName, setVarName] = useState(default) varName ➡ this.state = { varName: ... } setVarName(val) ➡ this.setState({ varName: val }) default ➡ this.state = { varName: default }
  20. @flxwu Built-in Hooks class UglyCounter extends React.Component { state =

    { counter: 0 }; render() { return ( <div> <p>You clicked {this.state.counter} times</p> <button onClick={this._onClick}> Click me </button> </div>) } _onClick = () => { this.setState({counter: this.state.counter + 1}); } } State Hook
  21. @flxwu React Hooks - Reacting to the hype State Hook

    Built-in Hooks function HooksCounter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } . . .
  22. @flxwu React Hooks - Reacting to the hype State Hook

    Built-in Hooks function HooksCounter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
  23. @flxwu React Hooks - Reacting to the hype State Hook

    Built-in Hooks const [count, setCount] = useState(0); . . . <button onClick={() => setCount(count + 1)}>
  24. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks ⚓ hooking into React lifecycles: useEffect( () => any side effects, [state variables to trigger this effect]) import React, { useEffect } from ‘react’;
  25. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks ⚓ hooking into React lifecycles: useEffect(() => any side effects) import React, { useEffect } from ‘react’;
  26. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks ⚓ componentDidMount ⏫ componentDidUpdate componentWillUnmount }useEffect
  27. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks function Stopwatch() { const [isOn, setIsOn] = useState(false); return ( <div> <button type="button" onClick={() => setIsOn(!isOn)}> {isOn ? 'Stop' : 'Start'} </button> </div> ); }
  28. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks function Stopwatch() { const [isOn, setIsOn] = useState(false); useEffect(() => { setInterval(() => console.log('tick'), 1000); }); return ( <div> <button type="button" onClick={() => setIsOn(!isOn)}> {isOn ? 'Stop' : 'Start'} </button> </div> ); }
  29. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(() => { setInterval(() => console.log('tick'), 1000); });
  30. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(() => { setInterval(() => console.log('tick'), 1000); }, []);
  31. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(() => { setInterval(() => console.log('tick'), 1000); }, []); ⬆ only called on mount / unmount
  32. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(() => { let interval = setInterval(() => console.log('tick'), 1000); return () => clearInterval(interval); }, []);
  33. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(() => { let interval = setInterval(() => console.log('tick'), 1000); return () => clearInterval(interval); }, []);
  34. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(() => { let interval; if (isOn)
 interval = setInterval(() => console.log('tick'), 1000); return () => clearInterval(interval); }, [isOn]);
  35. @flxwu Built-in Hooks function Stopwatch() { const [isOn, setIsOn] =

    useState(false); useEffect(() => { let interval; if (isOn)
 interval = setInterval(() => console.log('tick'), 1000); return () => clearInterval(interval); }, [isOn]); return ( <div> <button type="button" onClick={() => setIsOn(!isOn)}> {isOn ? 'Stop' : 'Start'} </button> </div> ); } Effect Hook
  36. @flxwu React Hooks - Reacting to the hype Effect Hook

    Built-in Hooks useEffect(function, array?) function => side-effect; return function to clean-up side-effect on unmount array? => only run effect if one of the state variables change on a rendering update
  37. @flxwu React Hooks - Reacting to the hype show display

    window width Custom Hooks ⚛ save current width in state ⏰ listen for window resize & update state
  38. @flxwu Custom Hooks function MyResponsiveComponent() { const width = useWindowWidth();

    // Our custom Hook return ( <p>Window width is {width}</p> ); }
  39. @flxwu Custom Hooks function OtherResponsiveComponent() { const width = useWindowWidth();

    // Our custom Hook return ( <p>Half of the width is {width / 2}</p> ); }
  40. @flxwu function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(()

    => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }); return width; } Custom Hooks
  41. @flxwu Custom Hooks function OtherResponsiveComponent() { const width = useWindowWidth();

    return ( <p>Half of the width is {width / 2}</p> ); } function MyResponsiveComponent() { const width = useWindowWidth(); return ( <p>Window width is {width}</p> ); }
  42. @flxwu React Hooks - Reacting to the hype TIL;Hooks are

    fully encapsulated — each time you call a Hook, it gets isolated local state within the currently executing component.
  43. @flxwu React Hooks - Reacting to the hype ✅ Reuse

    logic ✅ Smaller bundles and components
  44. @flxwu React Hooks - Reacting to the hype ✅ Reuse

    logic ✅ Smaller bundles and components ✅ Readable, simple code
  45. @flxwu React Hooks - Reacting to the hype Resources https:/

    /reactjs.org/docs/hooks-intro.html https:/ /medium.com/@dan_abramov/making-sense-of- react-hooks-fdbde8803889