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
85
React Hooks
Matija Marohnić
December 13, 2019
Tweet
Share
More Decks by Matija Marohnić
See All by Matija Marohnić
Goodbye jsdom/happy-dom, hello Vitest Browser Mode!
silvenon
0
10
Introduction to Remix
silvenon
0
150
Cypress vs. Playwright
silvenon
0
170
Studying Strapi: an open source head headless CMS
silvenon
0
48
CSS Specificity
silvenon
0
47
Make your JavaScript projects more accessible to newcomers
silvenon
0
80
PostCSS
silvenon
0
46
CSS Custom Properties
silvenon
0
42
Maintainable Integration Testing in React
silvenon
0
50
Other Decks in Programming
See All in Programming
2026年 エンジニアリング自己学習法
yumechi
0
150
CSC307 Lecture 12
javiergs
PRO
0
430
JPUG勉強会 OSSデータベースの内部構造を理解しよう
oga5
2
180
AIに仕事を丸投げしたら、本当に楽になれるのか
dip_tech
PRO
0
120
NetBSD+Raspberry Piで 本物のPSGを鳴らすデモを OSC駆動の7日間で作った話 / OSC2026Osaka
tsutsui
1
110
ノイジーネイバー問題を解決する 公平なキューイング
occhi
0
120
Oxlintはいいぞ
yug1224
5
1.4k
開発者から情シスまで - 多様なユーザー層に届けるAPI提供戦略 / Postman API Night Okinawa 2026 Winter
tasshi
0
230
浮動小数の比較について
kishikawakatsumi
0
240
AIエージェント、”どう作るか”で差は出るか? / AI Agents: Does the "How" Make a Difference?
rkaga
4
2.1k
Rust 製のコードエディタ “Zed” を使ってみた
nearme_tech
PRO
0
260
高速開発のためのコード整理術
sutetotanuki
1
420
Featured
See All Featured
How to make the Groovebox
asonas
2
2k
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
5
740
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
1
450
More Than Pixels: Becoming A User Experience Designer
marktimemedia
3
330
DevOps and Value Stream Thinking: Enabling flow, efficiency and business value
helenjbeal
1
130
Neural Spatial Audio Processing for Sound Field Analysis and Control
skoyamalab
0
180
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
0
69
Marketing Yourself as an Engineer | Alaka | Gurzu
gurzu
0
140
Side Projects
sachag
455
43k
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
62
50k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
1
58
Music & Morning Musume
bryan
47
7.1k
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