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
93
0
Share
React Hooks
Matija Marohnić
December 13, 2019
More Decks by Matija Marohnić
See All by Matija Marohnić
oxlint & oxfmt: linting and formatting from the future
silvenon
0
29
Goodbye jsdom/happy-dom, hello Vitest Browser Mode!
silvenon
0
19
Introduction to Remix
silvenon
0
160
Cypress vs. Playwright
silvenon
0
170
Studying Strapi: an open source head headless CMS
silvenon
0
55
CSS Specificity
silvenon
0
62
Make your JavaScript projects more accessible to newcomers
silvenon
0
91
PostCSS
silvenon
0
65
CSS Custom Properties
silvenon
0
52
Other Decks in Programming
See All in Programming
PHPで使える日時の表現と、その知り方 #frontend_phpcon_do
o0h
PRO
0
180
開発体験を左右するライブラリの API 設計 - GraphQL スキーマ構築ライブラリから考える #tskaigi
izumin5210
2
1.6k
今さら聞けないCancellationToken
htkym
0
220
Swiftのレキシカルスコープ管理
kntkymt
0
210
「エンジニアインターン、どうやって取った?」準備のリアルを語るLT会 Progate BAR
akiomatic
0
120
3Dシーンの圧縮
fadis
1
590
Signal Forms: Beyond the Basics @ngBaguette 2026 in Paris
manfredsteyer
PRO
0
220
ふつうのFeature Flag実践入門
irof
7
3.5k
キャリア迷子上等 ─ "ない道"は自分で作ればいい
16bitidol
2
190
AIとASP.NET Coreで雑Webアプリを作った話
mayuki
0
160
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.1k
Java × distroless で 軽量なコンテナイメージを / Java on Distroless
contour_gara
0
470
Featured
See All Featured
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
10k
The Language of Interfaces
destraynor
162
27k
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
380
Build The Right Thing And Hit Your Dates
maggiecrowley
39
3.2k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.5k
Tips & Tricks on How to Get Your First Job In Tech
honzajavorek
1
530
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
570
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1.3k
Site-Speed That Sticks
csswizardry
13
1.2k
It's Worth the Effort
3n
188
29k
Game over? The fight for quality and originality in the time of robots
wayneb77
1
190
Automating Front-end Workflow
addyosmani
1370
210k
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