Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
React Hooks
Search
Matija Marohnić
December 13, 2019
Programming
0
72
React Hooks
Matija Marohnić
December 13, 2019
Tweet
Share
More Decks by Matija Marohnić
See All by Matija Marohnić
Introduction to Remix
silvenon
0
140
Cypress vs. Playwright
silvenon
0
160
Studying Strapi: an open source head headless CMS
silvenon
0
38
CSS Specificity
silvenon
0
30
Make your JavaScript projects more accessible to newcomers
silvenon
0
73
PostCSS
silvenon
0
43
CSS Custom Properties
silvenon
0
40
Maintainable Integration Testing in React
silvenon
0
31
Writing Codemods with jscodeshift
silvenon
0
29
Other Decks in Programming
See All in Programming
Rancher と Terraform
fufuhu
2
180
AIレビュアーをスケールさせるには / Scaling AI Reviewers
technuma
2
240
テストカバレッジ100%を10年続けて得られた学びと品質
mottyzzz
2
420
AWS発のAIエディタKiroを使ってみた
iriikeita
1
140
【第4回】関東Kaggler会「Kaggleは執筆に役立つ」
mipypf
0
990
MCPで実現するAIエージェント駆動のNext.jsアプリデバッグ手法
nyatinte
7
1k
Namespace and Its Future
tagomoris
6
680
Laravel Boost 超入門
fire_arlo
2
170
AHC051解法紹介
eijirou
0
640
TanStack DB ~状態管理の新しい考え方~
bmthd
2
390
250830 IaCの選定~AWS SAMのLambdaをECSに乗り換えたときの備忘録~
east_takumi
0
350
CSC305 Summer Lecture 12
javiergs
PRO
0
130
Featured
See All Featured
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
33
2.4k
Agile that works and the tools we love
rasmusluckow
330
21k
Rails Girls Zürich Keynote
gr2m
95
14k
Facilitating Awesome Meetings
lara
55
6.5k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
61k
Why Our Code Smells
bkeepers
PRO
339
57k
Java REST API Framework Comparison - PWX 2021
mraible
33
8.8k
Code Reviewing Like a Champion
maltzj
525
40k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
18
1.1k
Designing Experiences People Love
moore
142
24k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
29
1.9k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
23
1.4k
Transcript
React Hooks
React Hooks • released in React 16.8 • a new
way to “hook into” React features • but first, let’s recap the API we have now
Class components
function MyComponent() { return <input type="email" "/> }
class MyComponent extends React.Component { state = { email: ''
} render() { return ( <input type="email" value={this.state.email} onChange={event "=> { this.setState({ email: event.target.value, }) }} "/> ); } }
function MyComponent({ value, onChange }) { return ( <input type="email"
value={value} onChange={onChange} "/> ) }
Pros • custom methods • reusing logic • naming logic
Cons • switching back and forth between functions and classes
• a lot of typing • noisy Git diffs • class components are weird • we don’t instantiate them • we don’t extend them
Lifecycle methods
class MyComponent extends React.Component { constructor(props) static getDerivedStateFromProps(props, state) render()
componentDidMount() shouldComponentUpdate(nextProps, nextState) getSnapshotBeforeUpdate(prevProps, prevState) componentDidUpdate(prevProps, prevState, snapshot) componentWillUnmount() }
Pros • transparency • descriptive method names • API is
well documented • fine-grained control • easily target exact moment in the lifecycle
Cons • no way to escape the complexity • memorizing
common pitfalls like endless loops • spreading a single feature across multiple methods
Higher-order components (HOCs)
import email from './hocs/email' function MyComponent({ email, handleEmailChange }) {
return ( <input type="email" value={email} onChange={handleEmailChange} "/> ) } export default email(MyComponent)
Pros • reusing complex behavior • we can keep using
function components
Cons • readability • all props are mixed together •
the HOC call is usually the last thing we see
Ok, back to hooks
None
Hooks • can only be used in function components •
they represent a new mental model
Lifecycle methods
Basic hooks • useState for local state • useEffect for
side-effects • useContext for applying context
import React from 'react' function MyComponent() { const [email, setEmail]
= React.useState('') return ( <input type="email" value={email} onChange={event "=> { setEmail(event.target.value) }} "/> ) }
Stateless or function components?
import React from 'react' function MyComponent() { React.useEffect(() "=> {
console.log('mounted') return () "=> { console.log('unmounted') } }, []) return "// ""... }
A must-read: A Complete Guide to useEffect by Dan Abramov
Additional hooks • useMemo for memoizing a computed value •
useCallback for memoizing a function reference • etc. https://reactjs.org/docs/hooks-reference.html
import React from 'react' import { computeExpensiveValue } from './utils/slow'
function MyComponent({ id }) { const value = React.useMemo(() "=> { return computeExpensiveValue(id) }, [id]) return "// ""... }
Read before memoizing • One simple trick to optimize React
re-renders • When to useMemo and useCallback
Custom hooks
import React from 'react' function useModal() { const CLASS_NAME =
'modal-open' React.useEffect(() "=> { document.body.classList.add(CLASS_NAME) return () "=> { document.body.classList.remove(CLASS_NAME) } }, []) }
Custom hooks recipes: usehooks.com
eslint-plugin-react-hooks
yarn install "--save-dev eslint-plugin-react-hooks module.exports = { plugins: [ 'react-hooks',
], rules: { 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn', } }
None
import React from 'react' import AnotherComponent from './AnotherComponent' function MyComponent({
id }) { const onClick = React.useCallback(() "=> { "// do something with id }, [id]) return ( <AnotherComponent onClick={onClick} "/> ) }
const onClick = React.useCallback(() "=> { "// do something with
id }, [id])
const onClick = React.useMemo(() "=> { return () "=> {
"// do something with id } }, [id])
import React from 'react' import AnotherComponent from './AnotherComponent' function MyComponent({
id }) { const onClick = React.useCallback(() "=> { "// do something with id }, [id]) return ( <AnotherComponent onClick={onClick} "/> ) }
Does AnotherComponent need reference equality?
import React from 'react' function AnotherComponent({ onClick }) { "//
expensive rendering } export default React.memo(AnotherComponent)
Pros • less typing, more thinking • reusing behavior is
nicer • no need for classes anymore…?
Cons • unlearning lifecycle methods • are there any more
cons? that’s up to you
Questions? @silvenon