SlideShare a Scribd company logo
13/04/2019 reveal.js
localhost:8000/?print-pdf 1/19
REACT HOOKS ⚓REACT HOOKS ⚓Felix Kühl - JobMatchMe GmbH
13/04/2019 reveal.js
localhost:8000/?print-pdf 2/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
statefull component
useState
class NameInput extends React.Component {
constructor(){
state = { name: "Max" }
}
handleChange = (e) => {
this.setState({name: e.target.value})
}
render(){ return <input type="text" onChange={this.handleChange} value={this.state} /> }
}
const NameInput = () => {
const [name, setName] = useState("Max")
const handleChange = (e) => {
setName(e.target.value)
}
return <input type="text" onChange={handleChange} value={name} />
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 3/19
WHY USESTATE IS ACUTALLYWHY USESTATE IS ACUTALLY
AWESOMEAWESOME
const Parent = () => {
const [name, setName] = useState()
return <Child setParentState={setName} />
}
const Child = ({setParentState}) => {
const upperCaseMe = () => {
setParentState((state) => state.toUpperCase())
})
return <button onClick={upperCaseMe}>Upper case my name!</button>
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 4/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
componentDidMount & componentDidUpdate
class TitleInput extends React.Component {
constructor(){
state = { title: "Hello" }
}
handleChange = (e) => {
this.setState({title: e.target.value})
}
componentDidMount() {
document.title = this.state.title
}
componentDidUpdate() {
document.title = this.state.title
}
render(){ return <input type="text" onChange={this.handleChange} value={this.state.title} /> }
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 5/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
useEffect
const TitleInput = () => {
const [title, setTitle] = useState("Hello")
const handleChange = (e) => {
setTitle.target.value)
}
useEffect(() => { document.title = title })
return <input type="text" onChange={handleChange} value={title} />
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 6/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
componentDidMount
class WidthComponent extends React.Component {
constructor(){
state = { width: window.innerWidth }
}
handleResize = () => {
this.setState({width: window.innerWidth})
}
componentDidMount() {
window.addEventListener('resize', this.handleResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize)
}
render(){ return <p>{this.state.width}</p> }
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 7/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
useEffect
const WidthComponent = () => {
const [width, setWidth] = useState(window.innerWidth)
const handleResize = () => {
setWidth(window.innerWidth)
}
useEffect(() => {
window.addEventListener('resize', handleResize)
return window.removeEventListener('resize', handleResize)
}, [])
return <p>{width}</p>
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 8/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
And what about componentDidUpdate?
13/04/2019 reveal.js
localhost:8000/?print-pdf 9/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
And what about componentDidUpdate?
useEffect(() => { if(iMightChange !== null) { doSomething() } }, [iMightChange])
13/04/2019 reveal.js
localhost:8000/?print-pdf 10/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
useContext
const Consumer = () => {
const value = useContext()
return (
<Context.Consumer>
{value => <p>Context says {value}</p>}
</Context.Consumer>
)
}
const Consumer = () => {
const value = useContext()
return (
<p>Context says {value}</p>
)
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 11/19
INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS
useMemo
const memoizedValue = useMemo(() => someExpensiveCalculation(x, y), [x, y]);
13/04/2019 reveal.js
localhost:8000/?print-pdf 12/19
REUSE AND COMPOSEREUSE AND COMPOSE
Are hooks kind of like mixins
const MyLocation = () => {
const location = useLocation()
return <p>You are at: {location}</p>
}
const useLocation = () => {
const [location, setLocation] = useState("loading...")
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(() =>
setLocation("lat: "+position.coords.latitude+" lng: "+position.coords.longitude)
);
} else {
return "Geolocation is not supported by this browser.";
}
})
return location
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 13/19
HOOKS IN REAL LIFEHOOKS IN REAL LIFE
Our (old) data provider
/* Context */
const DataContext = React.createContext()
/**
* Global user data provider
*
**/
class DataProvider extends React.Component {
constructor(props) {
super(props)
this.state = {
status: 'init',
data: parseData({}),
actions: {fetchData: this.fetchData}
}
}
/**
* Fetch Data only when we are authenticated. This might not happen on initial mounting
/
13/04/2019 reveal.js
localhost:8000/?print-pdf 14/19
HOOKS IN REAL LIFEHOOKS IN REAL LIFE
... now with hooks! ✨
/* Context */
export const DataContext = React.createContext()
/**
* Data Reducer
*/
const reducer = (state, action) => { ... }
/**
* Global user data provider
*
**/
const DataProvider = props => {
/**
* Fetch Data from API endpoint
*/
const fetchData = async () => { ... }
const [state, dispatch] = useReducer(reducer, {
'i i '
13/04/2019 reveal.js
localhost:8000/?print-pdf 15/19
HOOKS IN REAL LIFEHOOKS IN REAL LIFE
Class vs Hooks
async componentDidMount() {
if (this.props.authState === 'signedIn') {
await this.fetchData()
}
}
async componentDidUpdate(prevProps, prevState) {
if (
prevProps.authState !== this.props.authState &&
this.props.authState === 'signedIn'
) {
await this.fetchData()
}
}
useEffect(() => {
if (props.authState === 'signedIn') {
fetchData()
}
}, [props.authState])
13/04/2019 reveal.js
localhost:8000/?print-pdf 16/19
HOOKS UNDER THE HOODHOOKS UNDER THE HOOD
react / packages / react-reconciler / src / ReactFiberHooks.js
// TODO: Not sure if this is the desired semantics, but it's what we
// do for gDSFP. I can't remember why.
if (workInProgressHook.baseUpdate === queue.last) {
workInProgressHook.baseState = newState;
}
...
13/04/2019 reveal.js
localhost:8000/?print-pdf 17/19
HOOKS UNDER THE HOODHOOKS UNDER THE HOOD
https://medium.com/the-guild/under-the-hood-of-reacts-hooks-system-eb59638c9dba
13/04/2019 reveal.js
localhost:8000/?print-pdf 18/19
HOOKS UNDER THE HOODHOOKS UNDER THE HOOD
State object
State hooks queue
{
foo: 'foo',
bar: 'bar',
baz: 'baz',
}
{
memoizedState: 'foo',
next: {
memoizedState: 'bar',
next: {
memoizedState: 'bar',
next: null
}
}
}
13/04/2019 reveal.js
localhost:8000/?print-pdf 19/19
FINAL THOUGHTSFINAL THOUGHTS

More Related Content

What's hot

Evan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-redux
Evan Schultz
 
React redux
React reduxReact redux
React redux
Michel Perez
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Nir Kaufman
 
React&redux
React&reduxReact&redux
React&redux
Blank Chen
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
Christoffer Noring
 
Mobx - performance and sanity
Mobx - performance and sanityMobx - performance and sanity
Mobx - performance and sanity
500Tech
 
Extending Redux in the Server Side
Extending Redux in the Server SideExtending Redux in the Server Side
Extending Redux in the Server Side
Ignacio Martín
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity
500Tech
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
Christoffer Noring
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Ngrx: Redux in angular
Ngrx: Redux in angularNgrx: Redux in angular
Ngrx: Redux in angular
Saadnoor Salehin
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020
Jerry Liao
 
Ngrx
NgrxNgrx
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
NAVER SHOPPING
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
Nataliya Patsovska
 

What's hot (20)

Evan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-redux
 
React redux
React reduxReact redux
React redux
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
 
React&redux
React&reduxReact&redux
React&redux
 
React lecture
React lectureReact lecture
React lecture
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Mobx - performance and sanity
Mobx - performance and sanityMobx - performance and sanity
Mobx - performance and sanity
 
Extending Redux in the Server Side
Extending Redux in the Server SideExtending Redux in the Server Side
Extending Redux in the Server Side
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
 
Ngrx: Redux in angular
Ngrx: Redux in angularNgrx: Redux in angular
Ngrx: Redux in angular
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020
 
Ngrx
NgrxNgrx
Ngrx
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 

Similar to Deep Dive into React Hooks

Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Codemotion
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
Bryan Hsueh
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
Robert DeLuca
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
George Bukhanov
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JSFestUA
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
Boris Dinkevich
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
Pavel Lahoda
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
Droidcon Berlin
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with React
Thanh Trần Trọng
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworks
Eric Guo
 
Java 8 Hipster slides
Java 8 Hipster slidesJava 8 Hipster slides
Java 8 Hipster slides
Oleg Prophet
 
Developing Apps for Emerging Markets
Developing Apps for Emerging MarketsDeveloping Apps for Emerging Markets
Developing Apps for Emerging Markets
Annyce Davis
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflow
Alex Alexeev
 
How we manage React Microfrontends at JobMatchMe
How we manage React Microfrontends at JobMatchMeHow we manage React Microfrontends at JobMatchMe
How we manage React Microfrontends at JobMatchMe
Felix Kühl
 
No internet? No Problem!
No internet? No Problem!No internet? No Problem!
No internet? No Problem!
Annyce Davis
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]
Nilhcem
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
Dongho Cho
 
Framework
FrameworkFramework
SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!
Sébastien Levert
 

Similar to Deep Dive into React Hooks (20)

Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with React
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworks
 
Java 8 Hipster slides
Java 8 Hipster slidesJava 8 Hipster slides
Java 8 Hipster slides
 
Developing Apps for Emerging Markets
Developing Apps for Emerging MarketsDeveloping Apps for Emerging Markets
Developing Apps for Emerging Markets
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflow
 
How we manage React Microfrontends at JobMatchMe
How we manage React Microfrontends at JobMatchMeHow we manage React Microfrontends at JobMatchMe
How we manage React Microfrontends at JobMatchMe
 
No internet? No Problem!
No internet? No Problem!No internet? No Problem!
No internet? No Problem!
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Framework
FrameworkFramework
Framework
 
SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!
 

Recently uploaded

ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 

Recently uploaded (20)

ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 

Deep Dive into React Hooks

  • 1. 13/04/2019 reveal.js localhost:8000/?print-pdf 1/19 REACT HOOKS ⚓REACT HOOKS ⚓Felix Kühl - JobMatchMe GmbH
  • 2. 13/04/2019 reveal.js localhost:8000/?print-pdf 2/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS statefull component useState class NameInput extends React.Component { constructor(){ state = { name: "Max" } } handleChange = (e) => { this.setState({name: e.target.value}) } render(){ return <input type="text" onChange={this.handleChange} value={this.state} /> } } const NameInput = () => { const [name, setName] = useState("Max") const handleChange = (e) => { setName(e.target.value) } return <input type="text" onChange={handleChange} value={name} /> }
  • 3. 13/04/2019 reveal.js localhost:8000/?print-pdf 3/19 WHY USESTATE IS ACUTALLYWHY USESTATE IS ACUTALLY AWESOMEAWESOME const Parent = () => { const [name, setName] = useState() return <Child setParentState={setName} /> } const Child = ({setParentState}) => { const upperCaseMe = () => { setParentState((state) => state.toUpperCase()) }) return <button onClick={upperCaseMe}>Upper case my name!</button> }
  • 4. 13/04/2019 reveal.js localhost:8000/?print-pdf 4/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS componentDidMount & componentDidUpdate class TitleInput extends React.Component { constructor(){ state = { title: "Hello" } } handleChange = (e) => { this.setState({title: e.target.value}) } componentDidMount() { document.title = this.state.title } componentDidUpdate() { document.title = this.state.title } render(){ return <input type="text" onChange={this.handleChange} value={this.state.title} /> } }
  • 5. 13/04/2019 reveal.js localhost:8000/?print-pdf 5/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS useEffect const TitleInput = () => { const [title, setTitle] = useState("Hello") const handleChange = (e) => { setTitle.target.value) } useEffect(() => { document.title = title }) return <input type="text" onChange={handleChange} value={title} /> }
  • 6. 13/04/2019 reveal.js localhost:8000/?print-pdf 6/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS componentDidMount class WidthComponent extends React.Component { constructor(){ state = { width: window.innerWidth } } handleResize = () => { this.setState({width: window.innerWidth}) } componentDidMount() { window.addEventListener('resize', this.handleResize) } componentWillUnmount() { window.removeEventListener('resize', this.handleResize) } render(){ return <p>{this.state.width}</p> } }
  • 7. 13/04/2019 reveal.js localhost:8000/?print-pdf 7/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS useEffect const WidthComponent = () => { const [width, setWidth] = useState(window.innerWidth) const handleResize = () => { setWidth(window.innerWidth) } useEffect(() => { window.addEventListener('resize', handleResize) return window.removeEventListener('resize', handleResize) }, []) return <p>{width}</p> }
  • 8. 13/04/2019 reveal.js localhost:8000/?print-pdf 8/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS And what about componentDidUpdate?
  • 9. 13/04/2019 reveal.js localhost:8000/?print-pdf 9/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS And what about componentDidUpdate? useEffect(() => { if(iMightChange !== null) { doSomething() } }, [iMightChange])
  • 10. 13/04/2019 reveal.js localhost:8000/?print-pdf 10/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS useContext const Consumer = () => { const value = useContext() return ( <Context.Consumer> {value => <p>Context says {value}</p>} </Context.Consumer> ) } const Consumer = () => { const value = useContext() return ( <p>Context says {value}</p> ) }
  • 11. 13/04/2019 reveal.js localhost:8000/?print-pdf 11/19 INTRODUCTION TO HOOKSINTRODUCTION TO HOOKS useMemo const memoizedValue = useMemo(() => someExpensiveCalculation(x, y), [x, y]);
  • 12. 13/04/2019 reveal.js localhost:8000/?print-pdf 12/19 REUSE AND COMPOSEREUSE AND COMPOSE Are hooks kind of like mixins const MyLocation = () => { const location = useLocation() return <p>You are at: {location}</p> } const useLocation = () => { const [location, setLocation] = useState("loading...") useEffect(() => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(() => setLocation("lat: "+position.coords.latitude+" lng: "+position.coords.longitude) ); } else { return "Geolocation is not supported by this browser."; } }) return location }
  • 13. 13/04/2019 reveal.js localhost:8000/?print-pdf 13/19 HOOKS IN REAL LIFEHOOKS IN REAL LIFE Our (old) data provider /* Context */ const DataContext = React.createContext() /** * Global user data provider * **/ class DataProvider extends React.Component { constructor(props) { super(props) this.state = { status: 'init', data: parseData({}), actions: {fetchData: this.fetchData} } } /** * Fetch Data only when we are authenticated. This might not happen on initial mounting /
  • 14. 13/04/2019 reveal.js localhost:8000/?print-pdf 14/19 HOOKS IN REAL LIFEHOOKS IN REAL LIFE ... now with hooks! ✨ /* Context */ export const DataContext = React.createContext() /** * Data Reducer */ const reducer = (state, action) => { ... } /** * Global user data provider * **/ const DataProvider = props => { /** * Fetch Data from API endpoint */ const fetchData = async () => { ... } const [state, dispatch] = useReducer(reducer, { 'i i '
  • 15. 13/04/2019 reveal.js localhost:8000/?print-pdf 15/19 HOOKS IN REAL LIFEHOOKS IN REAL LIFE Class vs Hooks async componentDidMount() { if (this.props.authState === 'signedIn') { await this.fetchData() } } async componentDidUpdate(prevProps, prevState) { if ( prevProps.authState !== this.props.authState && this.props.authState === 'signedIn' ) { await this.fetchData() } } useEffect(() => { if (props.authState === 'signedIn') { fetchData() } }, [props.authState])
  • 16. 13/04/2019 reveal.js localhost:8000/?print-pdf 16/19 HOOKS UNDER THE HOODHOOKS UNDER THE HOOD react / packages / react-reconciler / src / ReactFiberHooks.js // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. if (workInProgressHook.baseUpdate === queue.last) { workInProgressHook.baseState = newState; } ...
  • 17. 13/04/2019 reveal.js localhost:8000/?print-pdf 17/19 HOOKS UNDER THE HOODHOOKS UNDER THE HOOD https://medium.com/the-guild/under-the-hood-of-reacts-hooks-system-eb59638c9dba
  • 18. 13/04/2019 reveal.js localhost:8000/?print-pdf 18/19 HOOKS UNDER THE HOODHOOKS UNDER THE HOOD State object State hooks queue { foo: 'foo', bar: 'bar', baz: 'baz', } { memoizedState: 'foo', next: { memoizedState: 'bar', next: { memoizedState: 'bar', next: null } } }