SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Evan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz
 
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 APIsMihail Gaberov
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Nir Kaufman
 
Mobx - performance and sanity
Mobx - performance and sanityMobx - performance and sanity
Mobx - performance and sanity500Tech
 
Extending Redux in the Server Side
Extending Redux in the Server SideExtending Redux in the Server Side
Extending Redux in the Server SideIgnacio Martín
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity500Tech
 
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 testingVisual Engineering
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max PetruckMaksym Petruk
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020Jerry Liao
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기NAVER SHOPPING
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonfNataliya Patsovska
 

Was ist angesagt? (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
 

Ähnlich wie React Hooks Introduction

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 2017Codemotion
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan 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 creatorsGeorge 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
 
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 developersPavel Lahoda
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon Berlin
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with ReactThanh Trần Trọng
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworksEric Guo
 
Java 8 Hipster slides
Java 8 Hipster slidesJava 8 Hipster slides
Java 8 Hipster slidesOleg Prophet
 
Developing Apps for Emerging Markets
Developing Apps for Emerging MarketsDeveloping Apps for Emerging Markets
Developing Apps for Emerging MarketsAnnyce Davis
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflowAlex 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 JobMatchMeFelix 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 PracticesYekmer 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/7Dongho Cho
 
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
 

Ähnlich wie React Hooks Introduction (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!
 

Kürzlich hochgeladen

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 

Kürzlich hochgeladen (20)

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 

React Hooks Introduction

  • 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 } } }