Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
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
110
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
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
54
Goodbye jsdom/happy-dom, hello Vitest Browser Mode!
silvenon
0
37
Introduction to Remix
silvenon
0
180
Cypress vs. Playwright
silvenon
0
190
Studying Strapi: an open source head headless CMS
silvenon
0
70
CSS Specificity
silvenon
0
80
Make your JavaScript projects more accessible to newcomers
silvenon
0
110
PostCSS
silvenon
0
76
CSS Custom Properties
silvenon
0
76
Other Decks in Programming
See All in Programming
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
550
Vapor Mode でアクセシビリティは 壊れないか検証した話
fuqda
1
310
Zero-Tap Sign-In対応、結局何をすればいいの?
mitohato14
0
1.4k
Long Living Tokens, Die, Die, Die! (or: The One Ring is Banned in Modern)
sylph01
0
400
우리의 Nitro Modules는 당신의 Turbo Modules보다 아름답다
l2hyunwoo
0
250
AIが生成したコードは読むべきか?抽象化設計とコードの品質保証 / abstraction-design-and-quality
minodriven
14
8.3k
まずはコードより業務と向き合う:テーブル解体のためにPdMを呼んだ話
sakawe_ee
0
120
AIで開発が速くなった先で、開発チームは何を目指すか
shihochan
1
2k
[Dev Group Paris Octobre 26] Agentforce, SIforce, Claudeforce, Slackbot… on s'y retrouve ?
nabondance
0
130
全ての永続トークンを、生まれる前に消し去りたい!
sylph01
3
1.7k
Groovy as a human and AI friendly programming language
paulk
0
170
HTML-in-Canvasで作る未来のWeb UI表現
clockmaker
5
6.2k
Featured
See All Featured
From Legacy to Launchpad: Building Startup-Ready Communities
dugsong
0
370
Git: the NoSQL Database
bkeepers
PRO
433
67k
BBQ
matthewcrist
90
10k
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
1
600
Done Done
chrislema
187
17k
Measuring Dark Social's Impact On Conversion and Attribution
stephenakadiri
2
320
Typedesign – Prime Four
hannesfritz
42
3.2k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
420
4 Signs Your Business is Dying
shpigford
187
23k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.9k
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
620
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
290
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