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
91
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
28
Goodbye jsdom/happy-dom, hello Vitest Browser Mode!
silvenon
0
17
Introduction to Remix
silvenon
0
150
Cypress vs. Playwright
silvenon
0
170
Studying Strapi: an open source head headless CMS
silvenon
0
55
CSS Specificity
silvenon
0
59
Make your JavaScript projects more accessible to newcomers
silvenon
0
89
PostCSS
silvenon
0
61
CSS Custom Properties
silvenon
0
52
Other Decks in Programming
See All in Programming
Agentic AI & UI: Arcitecture, HITL, Emerging Standards
manfredsteyer
PRO
0
100
AI時代のエンジニアリングの原則 / Engineering Principles in the AI Era
haru860
0
1.3k
When benchmarks go bad - what I learned from measuring performance wrong
hollycummins
0
390
サーバーレスで作る、動画データ管理基盤
oyasumipants
0
200
運転動画を検索可能にする〜Cosmos-Embed1とDatabricks Vector Searchで〜/cosmos-embed1-databricks-vector-search
studio_graph
3
950
ハーネスエンジニアリングとは?
kinopeee
13
7k
PHPer、Cloudflare に引っ越す
suguruooki
2
220
Programming with a DJ Controller — not vibe coding
m_seki
3
860
Structured Concurrency, Scoped Values and Joiners in the JDK 25 26 27
josepaumard
1
150
Spec Driven Development | AI Summit Vilnius
danielsogl
PRO
1
160
関係性から理解する"同一性"の型用語たち
pvcresin
1
140
AI時代になぜ書くのか
mutsumix
0
410
Featured
See All Featured
First, design no harm
axbom
PRO
2
1.2k
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
210
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.4k
How Software Deployment tools have changed in the past 20 years
geshan
0
33k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
1
52
Chasing Engaging Ingredients in Design
codingconduct
0
190
Design in an AI World
tapps
1
210
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
Become a Pro
speakerdeck
PRO
31
5.9k
A better future with KSS
kneath
240
18k
Faster Mobile Websites
deanohume
310
31k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
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