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
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
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
90
PostCSS
silvenon
0
65
CSS Custom Properties
silvenon
0
52
Other Decks in Programming
See All in Programming
Spec Driven Development | AI Summit Lisbon
danielsogl
PRO
0
120
These Five Tricks Can Make Your Apps Greener, Cheaper, & Nicer
hollycummins
0
270
Make SRE Operations Easier with Azure SRE Agent
kkamegawa
0
3.2k
生成AI時代にこそ効くGo | Why Go Works in the Age of Generative AI
mom0tomo
8
3.1k
正しくソフトウェアを作る、前提を疑うための認知の視点 / doubt-premise
minodriven
17
5.5k
Why Laravel apps break—Mastering the fundamentals to keep them maintainable
kentaroutakeda
1
330
プロパティの順序で型推論が壊れる!? TypeScript6.0の修正からContext-Sensitivityの仕組みを追う
bicstone
2
1.3k
AIエージェントと協働するCLI開発 — BunとOpenClawで学んだこと
yoshikouki
1
230
Inspired By RubyKaigi (EN)
atzzcokek
0
500
運用エージェントは "作る" から "育てる" へ - 記憶と自己進化の3層設計パターン / self-evolving-agents-three-layer-agent-design
gawa
12
3.4k
Java × distroless で 軽量なコンテナイメージを / Java on Distroless
contour_gara
0
460
RTSPクライアントを自作してみた話
simotin13
0
430
Featured
See All Featured
Thoughts on Productivity
jonyablonski
76
5.2k
Google's AI Overviews - The New Search
badams
0
1k
How GitHub (no longer) Works
holman
316
150k
Reflections from 52 weeks, 52 projects
jeffersonlam
356
21k
Avoiding the “Bad Training, Faster” Trap in the Age of AI
tmiket
0
170
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.9k
Amusing Abliteration
ianozsvald
1
190
The SEO Collaboration Effect
kristinabergwall1
1
470
What's in a price? How to price your products and services
michaelherold
247
13k
The World Runs on Bad Software
bkeepers
PRO
72
12k
Principles of Awesome APIs and How to Build Them.
keavy
128
17k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
930
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