SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Refactoring Into React Hooks
Matteo Antony Mistretta
Inglorious Coderz
@antonymistretta
Why
They separate stateful logic
They are composable functions
They keep our component hierarchy flat
They allow us to go fully functional
They are now stable
Separation Of Concerns
Pavel Prichodko's tweet
0:00
antony@ingloriouscoderz ~> whoami
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
Hello world!
Hello world!
class MyComponent extends Component {
state = { text: 'Hello world!' }
handleChange = event => {
this.setState({ text: event.target.value })
}
render() {
const { text } = this.state
return (
<>
<h1>{text}</h1>
<input value={text} onChange={this.handleChange} />
</>
)
}
}
render(MyComponent)
Hello world!
Hello world!
function MyComponent() {
const [text, setText] = useState('Hello world!')
const handleChange = event => setText(event.target.value)
return (
<>
<h1>{text}</h1>
<input value={text} onChange={handleChange} />
</>
)
}
render(MyComponent)
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
Focus!
class MyComponent extends Component {
myRef = React.createRef()
handleClick = () => this.myRef.current.focus()
render() {
return (
<div className="input-group">
<input defaultValue="Hello world!" ref={this.myRef} />
<button onClick={this.handleClick}>Focus!</button>
</div>
)
}
}
render(MyComponent)
Hello worl
Focus!
function MyComponent() {
const myRef = useRef()
const handleClick = () => myRef.current.focus()
return (
<div className="input-group">
<input defaultValue="Hello world!" ref={myRef} />
<button onClick={handleClick}>Focus!</button>
</div>
)
}
render(MyComponent)
Hello worl
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
0
Play
class MyComponent extends Component {
state = { play: false, count: 0 }
toggle = () => this.setState(({ play }) => ({ play: !play }))
tick = () => this.setState(({ count }) => ({ count: count + 1 }))
start = () => (this.interval = setInterval(this.tick, 1000))
stop = () => clearInterval(this.interval)
componentDidMount() {
const { play } = this.state
if (play) {
this.start()
}
}
componentDidUpdate(prevProps, prevState) {
const { play } = this.state
if (play !== prevState.play) {
if (play) {
this.start()
} else {
this.stop()
}
}
}
componentWillUnmount() {
this.stop()
}
render() {
const { count, play } = this.state
return (
<>
<h1>{count}</h1>
<button onClick={this.toggle}>{play ? 'Pause' : 'Play'}</button>
</>
)
}
}
render(MyComponent)
0
Play
function MyComponent() {
const [play, setPlay] = useState(false)
const [count, setCount] = useState(0)
const toggle = () => setPlay(play => !play)
useEffect(() => {
let interval = null
const tick = () => setCount(count => count + 1)
const start = () => (interval = setInterval(tick, 1000))
const stop = () => clearInterval(interval)
if (play) {
start()
} else {
stop()
}
return () => stop()
}, [play])
return (
<>
<h1>{count}</h1>
<button onClick={toggle}>{play ? 'Pause' : 'Play'}</button>
</>
)
}
render(MyComponent)
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
Hello world!
Hello world!
const enhance = compose(
withState('text', 'setText', 'Hello world!'),
withHandlers({
onChange: ({ setText }) => event => setText(event.target.value),
}),
pure,
)
function MyComponent({ text, onChange }) {
return (
<>
<h1>{text}</h1>
<input value={text} onChange={onChange} />
</>
)
}
render(enhance(MyComponent))
Hello world!
Hello world!
function useText() {
const [text, setText] = useState('Hello world!')
const handleChange = event => setText(event.target.value)
return { value: text, onChange: handleChange }
}
function MyComponent() {
const text = useText()
return (
<>
<h1>{text.value}</h1>
<input {...text} />
</>
)
}
render(memo(MyComponent))
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
Turn on
function Parent() {
return (
<Toggler
defaultOn={false}
render={({ on, toggle }) => <Child on={on} toggle={toggle} />}
/>
)
}
function Child({ on, toggle }) {
return <button onClick={toggle}>{on ? 'Turn off' : 'Turn on'}</button>
}
class Toggler extends Component {
state = { on: this.props.defaultOn }
toggle = () => this.setState(({ on }) => ({ on: !on }))
render() {
const { render } = this.props
const { on } = this.state
return render({ on, toggle: this.toggle })
}
}
render(Parent)
Turn on
function Parent() {
const toggler = useToggler(false)
return <Child {...toggler} />
}
function Child({ on, toggle }) {
return <button onClick={toggle}>{on ? 'Turn off' : 'Turn on'}</button>
}
function useToggler(defaultOn) {
const [on, setOn] = useState(defaultOn)
const toggle = useCallback(() => setOn(!on), [on])
return { on, toggle }
}
render(Parent)
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
Hello
Antony!
const UserContext = createContext()
const ThemeContext = createContext()
function Parent() {
return (
<UserContext.Provider value="Antony">
<ThemeContext.Provider value={{ color: '#e06c75' }}>
<Child />
</ThemeContext.Provider>
</UserContext.Provider>
)
}
function Child() {
return (
<UserContext.Consumer>
{user => (
<ThemeContext.Consumer>
{theme => <h1 style={theme}>Hello {user}!</h1>}
</ThemeContext.Consumer>
)}
</UserContext.Consumer>
)
}
render(Parent)
Hello
Antony!
const UserContext = createContext()
const ThemeContext = createContext()
function Parent() {
return (
<UserContext.Provider value="Antony">
<ThemeContext.Provider value={{ color: '#e06c75' }}>
<Child />
</ThemeContext.Provider>
</UserContext.Provider>
)
}
function Child() {
const user = useContext(UserContext)
const theme = useContext(ThemeContext)
return <h1 style={theme}>Hello {user}!</h1>
}
render(Parent)
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
0
-1 +1
function counter(state = 0, action) {
const { type, payload } = action
switch (type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
case 'SET_COUNT':
return payload
default:
return state
}
}
const enhance = compose(
withReducer('count', 'dispatch', counter, 0),
withHandlers({
increment: ({ dispatch }) => () => dispatch({ type: 'INCREMENT' }),
decrement: ({ dispatch }) => () => dispatch({ type: 'DECREMENT' }),
setCount: ({ dispatch }) => value =>
dispatch({ type: 'SET_COUNT', payload: value }),
}),
withHandlers({
handleChange: ({ setCount }) => event =>
setCount(parseInt(event.target.value)),
}),
)
function Counter({ count, increment, decrement, handleChange }) {
return (
<>
<h1>{count}</h1>
<div className="input-group">
<button onClick={decrement}>-1</button>
<input type="number" value={count} onChange={handleChange} />
<button onClick={increment}>+1</button>
</div>
</>
)
}
render(enhance(Counter))
0
0
-1 +1
function useCounter() {
const [count, dispatch] = useReducer(counter, 0)
const increment = () => dispatch({ type: 'INCREMENT' })
const decrement = () => dispatch({ type: 'DECREMENT' })
const setCount = value => dispatch({ type: 'SET_COUNT', payload: value })
const handleChange = event => setCount(parseInt(event.target.value))
return { count, increment, decrement, handleChange }
}
function Counter() {
const { count, increment, decrement, handleChange } = useCounter()
return (
<>
<h1>{count}</h1>
<div className="input-group">
<button onClick={decrement}>-1</button>
<input type="number" value={count} onChange={handleChange} />
<button onClick={increment}>+1</button>
</div>
</>
)
}
render(Counter)
function counter(state = 0, action) {
const { type, payload } = action
switch (type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
case 'SET_COUNT':
return payload
default:
return state
}
}
0
Let's refactor...
1. State
2. Refs and Instance Attributes
3. Lifecycle Methods
4. Higher-Order Components
5. Render Props
6. Context API
7. Reducers
8. Redux
0
-1 +10
const CounterContext = createContext()
class Parent extends Component {
dispatch = action =>
this.setState(({ count }) => ({ count: counter(count, action) }))
increment = () => this.dispatch({ type: 'INCREMENT' })
decrement = () => this.dispatch({ type: 'DECREMENT' })
setCount = value => this.dispatch({ type: 'SET_COUNT', payload: value })
handleChange = event => this.setCount(parseInt(event.target.value))
state = {
count: 0,
increment: this.increment,
decrement: this.decrement,
handleChange: this.handleChange,
}
render() {
return (
<CounterContext.Provider value={this.state}>
<Child />
</CounterContext.Provider>
)
}
}
function Child() {
const { count, increment, decrement, handleChange } = useContext(
CounterContext,
)
return (
<>
<h1>{count}</h1>
<div className="input-group">
<button onClick={decrement}>-1</button>
<input type="number" value={count} onChange={handleChange} />
<button onClick={increment}>+1</button>
</div>
</>
)
}
render(Parent)
function counter(state = 0, action) {
const { type, payload } = action
0
-1 +10
const CounterContext = createContext()
function Parent() {
const counter = useCounter()
return (
<CounterContext.Provider value={counter}>
<Child />
</CounterContext.Provider>
)
}
function Child() {
const { count, increment, decrement, handleChange } = useContext(
CounterContext,
)
return (
<>
<h1>{count}</h1>
<div className="input-group">
<button onClick={decrement}>-1</button>
<input type="number" value={count} onChange={handleChange} />
<button onClick={increment}>+1</button>
</div>
</>
)
}
render(Parent)
function counter(state = 0, action) {
const { type, payload } = action
switch (type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
case 'SET_COUNT':
return payload
default:
return state
}
}
function useCounter() {
const [count, dispatch] = useReducer(counter, 0)
const increment = () => dispatch({ type: 'INCREMENT' })
const decrement = () => dispatch({ type: 'DECREMENT' })
Hooks:
Simplify and organize code
Are composable
Will give performance gains
Are subject to rules
Are still completely optional
Will not replace everything else
Thank you.
Questions?
html | pdf | source

Mais conteúdo relacionado

Mais procurados

Design pattern - Iterator, Mediator and Memento
Design pattern - Iterator, Mediator and MementoDesign pattern - Iterator, Mediator and Memento
Design pattern - Iterator, Mediator and MementoSean Tsai
 
Blender-like SceneView Hotkeys Unity extensions
Blender-like SceneView Hotkeys Unity extensionsBlender-like SceneView Hotkeys Unity extensions
Blender-like SceneView Hotkeys Unity extensionsKoji Hasegawa
 
Vuexと入力フォーム
Vuexと入力フォームVuexと入力フォーム
Vuexと入力フォームJoe_noh
 
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...tdc-globalcode
 
Android Architecture Component in Real Life
Android Architecture Component in Real LifeAndroid Architecture Component in Real Life
Android Architecture Component in Real LifeSomkiat Khitwongwattana
 
Basically Redux - Android Listeners
Basically Redux - Android ListenersBasically Redux - Android Listeners
Basically Redux - Android ListenersCody Engel
 
Architecture Components In Real Life Season 2
Architecture Components In Real Life Season 2Architecture Components In Real Life Season 2
Architecture Components In Real Life Season 2Somkiat Khitwongwattana
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #statesKonstantin Käfer
 
Kivy Talk Python Meetup Innsbruck 2017.04.25
Kivy Talk Python Meetup Innsbruck 2017.04.25Kivy Talk Python Meetup Innsbruck 2017.04.25
Kivy Talk Python Meetup Innsbruck 2017.04.25Robert Niederreiter
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitonsgarbles
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 
Designing Immutability Data Flows in Ember
Designing Immutability Data Flows in EmberDesigning Immutability Data Flows in Ember
Designing Immutability Data Flows in EmberJorge Lainfiesta
 
State managment in a world of hooks
State managment in a world of hooksState managment in a world of hooks
State managment in a world of hooks500Tech
 
Storyboards Slides
Storyboards SlidesStoryboards Slides
Storyboards Slidesmobiledevnj
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2stuq
 
YUI3 Modules
YUI3 ModulesYUI3 Modules
YUI3 Modulesa_pipkin
 

Mais procurados (20)

Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
Design pattern - Iterator, Mediator and Memento
Design pattern - Iterator, Mediator and MementoDesign pattern - Iterator, Mediator and Memento
Design pattern - Iterator, Mediator and Memento
 
Blender-like SceneView Hotkeys Unity extensions
Blender-like SceneView Hotkeys Unity extensionsBlender-like SceneView Hotkeys Unity extensions
Blender-like SceneView Hotkeys Unity extensions
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Vuexと入力フォーム
Vuexと入力フォームVuexと入力フォーム
Vuexと入力フォーム
 
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
 
Android Architecture Component in Real Life
Android Architecture Component in Real LifeAndroid Architecture Component in Real Life
Android Architecture Component in Real Life
 
Basically Redux - Android Listeners
Basically Redux - Android ListenersBasically Redux - Android Listeners
Basically Redux - Android Listeners
 
Architecture Components In Real Life Season 2
Architecture Components In Real Life Season 2Architecture Components In Real Life Season 2
Architecture Components In Real Life Season 2
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
 
Kivy Talk Python Meetup Innsbruck 2017.04.25
Kivy Talk Python Meetup Innsbruck 2017.04.25Kivy Talk Python Meetup Innsbruck 2017.04.25
Kivy Talk Python Meetup Innsbruck 2017.04.25
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Designing Immutability Data Flows in Ember
Designing Immutability Data Flows in EmberDesigning Immutability Data Flows in Ember
Designing Immutability Data Flows in Ember
 
The Settings API
The Settings APIThe Settings API
The Settings API
 
State managment in a world of hooks
State managment in a world of hooksState managment in a world of hooks
State managment in a world of hooks
 
New text document
New text documentNew text document
New text document
 
Storyboards Slides
Storyboards SlidesStoryboards Slides
Storyboards Slides
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
YUI3 Modules
YUI3 ModulesYUI3 Modules
YUI3 Modules
 

Semelhante a Matteo Antony Mistretta - Refactoring into React hooks - Codemotion Rome 2019

React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooksJim Liu
 
React JS Hooks Sheet .pdf
React JS Hooks Sheet .pdfReact JS Hooks Sheet .pdf
React JS Hooks Sheet .pdfnishant078cs23
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020Jerry Liao
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JSFestUA
 
react-hooks.pdf
react-hooks.pdfreact-hooks.pdf
react-hooks.pdfchengbo xu
 
Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Augustin Bralley
 
Sequencing Audio Using React and the Web Audio API
Sequencing Audio Using React and the Web Audio APISequencing Audio Using React and the Web Audio API
Sequencing Audio Using React and the Web Audio APIVincent Riemer
 
How Reactive do we need to be
How Reactive do we need to beHow Reactive do we need to be
How Reactive do we need to beJana Karceska
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Powering code reuse with context and render props
Powering code reuse with context and render propsPowering code reuse with context and render props
Powering code reuse with context and render propsForbes Lindesay
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxLoiane Groner
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
JS Lab2017_Lightning Talks_React Perfomance
JS Lab2017_Lightning Talks_React Perfomance JS Lab2017_Lightning Talks_React Perfomance
JS Lab2017_Lightning Talks_React Perfomance GeeksLab Odessa
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeAnton Kulyk
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projectsIgnacio Martín
 

Semelhante a Matteo Antony Mistretta - Refactoring into React hooks - Codemotion Rome 2019 (20)

React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooks
 
React JS Hooks Sheet .pdf
React JS Hooks Sheet .pdfReact JS Hooks Sheet .pdf
React JS Hooks Sheet .pdf
 
React hooks
React hooksReact hooks
React hooks
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
 
react-hooks.pdf
react-hooks.pdfreact-hooks.pdf
react-hooks.pdf
 
ReactJS
ReactJSReactJS
ReactJS
 
Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1
 
Sequencing Audio Using React and the Web Audio API
Sequencing Audio Using React and the Web Audio APISequencing Audio Using React and the Web Audio API
Sequencing Audio Using React and the Web Audio API
 
How Reactive do we need to be
How Reactive do we need to beHow Reactive do we need to be
How Reactive do we need to be
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Powering code reuse with context and render props
Powering code reuse with context and render propsPowering code reuse with context and render props
Powering code reuse with context and render props
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRx
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
JS Lab2017_Lightning Talks_React Perfomance
JS Lab2017_Lightning Talks_React Perfomance JS Lab2017_Lightning Talks_React Perfomance
JS Lab2017_Lightning Talks_React Perfomance
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React Native
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 

Mais de Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

Mais de Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Último

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Último (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Matteo Antony Mistretta - Refactoring into React hooks - Codemotion Rome 2019

  • 1. Refactoring Into React Hooks Matteo Antony Mistretta Inglorious Coderz @antonymistretta
  • 2. Why They separate stateful logic They are composable functions They keep our component hierarchy flat They allow us to go fully functional They are now stable
  • 3. Separation Of Concerns Pavel Prichodko's tweet 0:00
  • 5.
  • 6. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 7. Hello world! Hello world! class MyComponent extends Component { state = { text: 'Hello world!' } handleChange = event => { this.setState({ text: event.target.value }) } render() { const { text } = this.state return ( <> <h1>{text}</h1> <input value={text} onChange={this.handleChange} /> </> ) } } render(MyComponent)
  • 8. Hello world! Hello world! function MyComponent() { const [text, setText] = useState('Hello world!') const handleChange = event => setText(event.target.value) return ( <> <h1>{text}</h1> <input value={text} onChange={handleChange} /> </> ) } render(MyComponent)
  • 9. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 10. Focus! class MyComponent extends Component { myRef = React.createRef() handleClick = () => this.myRef.current.focus() render() { return ( <div className="input-group"> <input defaultValue="Hello world!" ref={this.myRef} /> <button onClick={this.handleClick}>Focus!</button> </div> ) } } render(MyComponent) Hello worl
  • 11. Focus! function MyComponent() { const myRef = useRef() const handleClick = () => myRef.current.focus() return ( <div className="input-group"> <input defaultValue="Hello world!" ref={myRef} /> <button onClick={handleClick}>Focus!</button> </div> ) } render(MyComponent) Hello worl
  • 12. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 13. 0 Play class MyComponent extends Component { state = { play: false, count: 0 } toggle = () => this.setState(({ play }) => ({ play: !play })) tick = () => this.setState(({ count }) => ({ count: count + 1 })) start = () => (this.interval = setInterval(this.tick, 1000)) stop = () => clearInterval(this.interval) componentDidMount() { const { play } = this.state if (play) { this.start() } } componentDidUpdate(prevProps, prevState) { const { play } = this.state if (play !== prevState.play) { if (play) { this.start() } else { this.stop() } } } componentWillUnmount() { this.stop() } render() { const { count, play } = this.state return ( <> <h1>{count}</h1> <button onClick={this.toggle}>{play ? 'Pause' : 'Play'}</button> </> ) } } render(MyComponent)
  • 14. 0 Play function MyComponent() { const [play, setPlay] = useState(false) const [count, setCount] = useState(0) const toggle = () => setPlay(play => !play) useEffect(() => { let interval = null const tick = () => setCount(count => count + 1) const start = () => (interval = setInterval(tick, 1000)) const stop = () => clearInterval(interval) if (play) { start() } else { stop() } return () => stop() }, [play]) return ( <> <h1>{count}</h1> <button onClick={toggle}>{play ? 'Pause' : 'Play'}</button> </> ) } render(MyComponent)
  • 15. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 16.
  • 17.
  • 18.
  • 19. Hello world! Hello world! const enhance = compose( withState('text', 'setText', 'Hello world!'), withHandlers({ onChange: ({ setText }) => event => setText(event.target.value), }), pure, ) function MyComponent({ text, onChange }) { return ( <> <h1>{text}</h1> <input value={text} onChange={onChange} /> </> ) } render(enhance(MyComponent))
  • 20. Hello world! Hello world! function useText() { const [text, setText] = useState('Hello world!') const handleChange = event => setText(event.target.value) return { value: text, onChange: handleChange } } function MyComponent() { const text = useText() return ( <> <h1>{text.value}</h1> <input {...text} /> </> ) } render(memo(MyComponent))
  • 21. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 22. Turn on function Parent() { return ( <Toggler defaultOn={false} render={({ on, toggle }) => <Child on={on} toggle={toggle} />} /> ) } function Child({ on, toggle }) { return <button onClick={toggle}>{on ? 'Turn off' : 'Turn on'}</button> } class Toggler extends Component { state = { on: this.props.defaultOn } toggle = () => this.setState(({ on }) => ({ on: !on })) render() { const { render } = this.props const { on } = this.state return render({ on, toggle: this.toggle }) } } render(Parent)
  • 23. Turn on function Parent() { const toggler = useToggler(false) return <Child {...toggler} /> } function Child({ on, toggle }) { return <button onClick={toggle}>{on ? 'Turn off' : 'Turn on'}</button> } function useToggler(defaultOn) { const [on, setOn] = useState(defaultOn) const toggle = useCallback(() => setOn(!on), [on]) return { on, toggle } } render(Parent)
  • 24. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 25. Hello Antony! const UserContext = createContext() const ThemeContext = createContext() function Parent() { return ( <UserContext.Provider value="Antony"> <ThemeContext.Provider value={{ color: '#e06c75' }}> <Child /> </ThemeContext.Provider> </UserContext.Provider> ) } function Child() { return ( <UserContext.Consumer> {user => ( <ThemeContext.Consumer> {theme => <h1 style={theme}>Hello {user}!</h1>} </ThemeContext.Consumer> )} </UserContext.Consumer> ) } render(Parent)
  • 26. Hello Antony! const UserContext = createContext() const ThemeContext = createContext() function Parent() { return ( <UserContext.Provider value="Antony"> <ThemeContext.Provider value={{ color: '#e06c75' }}> <Child /> </ThemeContext.Provider> </UserContext.Provider> ) } function Child() { const user = useContext(UserContext) const theme = useContext(ThemeContext) return <h1 style={theme}>Hello {user}!</h1> } render(Parent)
  • 27. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 28. 0 -1 +1 function counter(state = 0, action) { const { type, payload } = action switch (type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 case 'SET_COUNT': return payload default: return state } } const enhance = compose( withReducer('count', 'dispatch', counter, 0), withHandlers({ increment: ({ dispatch }) => () => dispatch({ type: 'INCREMENT' }), decrement: ({ dispatch }) => () => dispatch({ type: 'DECREMENT' }), setCount: ({ dispatch }) => value => dispatch({ type: 'SET_COUNT', payload: value }), }), withHandlers({ handleChange: ({ setCount }) => event => setCount(parseInt(event.target.value)), }), ) function Counter({ count, increment, decrement, handleChange }) { return ( <> <h1>{count}</h1> <div className="input-group"> <button onClick={decrement}>-1</button> <input type="number" value={count} onChange={handleChange} /> <button onClick={increment}>+1</button> </div> </> ) } render(enhance(Counter)) 0
  • 29. 0 -1 +1 function useCounter() { const [count, dispatch] = useReducer(counter, 0) const increment = () => dispatch({ type: 'INCREMENT' }) const decrement = () => dispatch({ type: 'DECREMENT' }) const setCount = value => dispatch({ type: 'SET_COUNT', payload: value }) const handleChange = event => setCount(parseInt(event.target.value)) return { count, increment, decrement, handleChange } } function Counter() { const { count, increment, decrement, handleChange } = useCounter() return ( <> <h1>{count}</h1> <div className="input-group"> <button onClick={decrement}>-1</button> <input type="number" value={count} onChange={handleChange} /> <button onClick={increment}>+1</button> </div> </> ) } render(Counter) function counter(state = 0, action) { const { type, payload } = action switch (type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 case 'SET_COUNT': return payload default: return state } } 0
  • 30. Let's refactor... 1. State 2. Refs and Instance Attributes 3. Lifecycle Methods 4. Higher-Order Components 5. Render Props 6. Context API 7. Reducers 8. Redux
  • 31. 0 -1 +10 const CounterContext = createContext() class Parent extends Component { dispatch = action => this.setState(({ count }) => ({ count: counter(count, action) })) increment = () => this.dispatch({ type: 'INCREMENT' }) decrement = () => this.dispatch({ type: 'DECREMENT' }) setCount = value => this.dispatch({ type: 'SET_COUNT', payload: value }) handleChange = event => this.setCount(parseInt(event.target.value)) state = { count: 0, increment: this.increment, decrement: this.decrement, handleChange: this.handleChange, } render() { return ( <CounterContext.Provider value={this.state}> <Child /> </CounterContext.Provider> ) } } function Child() { const { count, increment, decrement, handleChange } = useContext( CounterContext, ) return ( <> <h1>{count}</h1> <div className="input-group"> <button onClick={decrement}>-1</button> <input type="number" value={count} onChange={handleChange} /> <button onClick={increment}>+1</button> </div> </> ) } render(Parent) function counter(state = 0, action) { const { type, payload } = action
  • 32. 0 -1 +10 const CounterContext = createContext() function Parent() { const counter = useCounter() return ( <CounterContext.Provider value={counter}> <Child /> </CounterContext.Provider> ) } function Child() { const { count, increment, decrement, handleChange } = useContext( CounterContext, ) return ( <> <h1>{count}</h1> <div className="input-group"> <button onClick={decrement}>-1</button> <input type="number" value={count} onChange={handleChange} /> <button onClick={increment}>+1</button> </div> </> ) } render(Parent) function counter(state = 0, action) { const { type, payload } = action switch (type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 case 'SET_COUNT': return payload default: return state } } function useCounter() { const [count, dispatch] = useReducer(counter, 0) const increment = () => dispatch({ type: 'INCREMENT' }) const decrement = () => dispatch({ type: 'DECREMENT' })
  • 33. Hooks: Simplify and organize code Are composable Will give performance gains Are subject to rules Are still completely optional Will not replace everything else