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
62
React Hooks
Matija Marohnić
December 13, 2019
Tweet
Share
More Decks by Matija Marohnić
See All by Matija Marohnić
Introduction to Remix
silvenon
0
120
Cypress vs. Playwright
silvenon
0
140
Studying Strapi: an open source head headless CMS
silvenon
0
28
CSS Specificity
silvenon
0
21
Make your JavaScript projects more accessible to newcomers
silvenon
0
63
PostCSS
silvenon
0
35
CSS Custom Properties
silvenon
0
34
Maintainable Integration Testing in React
silvenon
0
22
Writing Codemods with jscodeshift
silvenon
0
21
Other Decks in Programming
See All in Programming
【re:Growth 2024】 Aurora DSQL をちゃんと話します!
maroon1st
0
770
CSC305 Lecture 26
javiergs
PRO
0
140
バグを見つけた?それAppleに直してもらおう!
uetyo
0
180
KMP와 kotlinx.rpc로 서버와 클라이언트 동기화
kwakeuijin
0
140
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
710
Mermaid x AST x 生成AI = コードとドキュメントの完全同期への道
shibuyamizuho
0
160
Recoilを剥がしている話
kirik
5
6.6k
PHPで作るWebSocketサーバー ~リアクティブなアプリケーションを知るために~ / WebSocket Server in PHP - To know reactive applications
seike460
PRO
2
110
Jakarta EE meets AI
ivargrimstad
0
240
短期間での新規プロダクト開発における「コスパの良い」Goのテスト戦略」 / kamakura.go
n3xem
2
170
ブラウザ単体でmp4書き出すまで - muddy-web - 2024-12
yue4u
2
460
ドメインイベント増えすぎ問題
h0r15h0
1
230
Featured
See All Featured
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
Mobile First: as difficult as doing things right
swwweet
222
9k
Large-scale JavaScript Application Architecture
addyosmani
510
110k
Unsuck your backbone
ammeep
669
57k
Docker and Python
trallard
42
3.1k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
111
49k
Fashionably flexible responsive web design (full day workshop)
malarkey
405
66k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
32
2.7k
For a Future-Friendly Web
brad_frost
175
9.4k
Why You Should Never Use an ORM
jnunemaker
PRO
54
9.1k
The World Runs on Bad Software
bkeepers
PRO
65
11k
Why Our Code Smells
bkeepers
PRO
335
57k
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