SlideShare a Scribd company logo
1 of 43
Managing Complex UI with xState
Xavier “X” Lozinguez
Staff Software Engineer @ Jet
Customer Experience Team (Batman)
• French
• PADI Certified Scuba Diver
• BJJ student
Contact
• xavier.lozinguez@jet.com
• @xlozinguez (Github, Twitter)
• http://xavier.lozinguez.com
Agenda
• State Machine? State Charts?
• Example of a “complex” UI
• xState overview
• xState + React
• Q&A
State Machine?
State Charts?
Finite State Machine – ex: traffic light
• Finite amount of states
• Predetermined sequenced transitions
Green Red
Yellow
TIME
R
TIME
R
TIME
R
• Events triggers transitions
State Chart
created by David Harel in 1987
A state chart is a state machine
composed of other state
machines called sub-states.
Sub-states can be state charts
themselves (compound states)
or remain atomic.
Allow for advanced state
composition using hierarchical,
historic and parallel states.
State Chart – ex: traffic light
Green
Yellow
TIME
R
TIME
R
TIME
R
Red
State Chart – ex: traffic light
Green
Yellow
TIME
R
TIME
R
TIME
R
Wal
k
Wai
t
Sto
p
PED_TIM
ER
PED_TIM
ER
Red
Okay… but why? 9
• Tried-and-true methodology for modeling
applications
• Makes the impossible impossible
• Allow for application logic visualization
Complex UI example
Complex UI example
Source: https://material.io/design/interaction/selection.html#item-
Browsing State
CREATE_NEW_ITEM
BROWSE_FOLDERS
SELECT_ITEM
VIEW_ITEM
SEARCH
TOGGLE_VIEW
DISPLAY_INFO
Selecting State
DESELECT_ITEM
RESET_SELECTION
SHARE_SELECTION
DELETE_SELECTION
MOVE_SELECTION_TO_FOLD
SELECT_ITEM
Global State Chart – Browsing & Selecting
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
SELECT_ITEM
RESET_SELECTION
What about
DELETE_SELECTION?
DESELECT_ITEM
(if selectedItems.length >
0)
Global State Chart – Deleting & Prompting
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState
xState by David Khourshid (davidkpiano)
Global State Chart – Events
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart – Events
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState – Events 20
Composed of a type and an
optional payload
Payload is then handed over to
actions for side-effect purpose
Events cause a state machine to transition from its current state to
the next
type IAppEvent =
| { type: 'SELECT_ITEM', item }
| { type: 'SELECT_ALL_ITEMS’ }
| { type: 'DESELECT_ITEM', item }
| { type: 'DELETE_SELECTION’ }
| { type: 'SELECTION_DELETED’ }
| { type: 'RESET_SELECTION’ }
| { type: 'DISMISS_PROMPT' };
xState: Machine Configuration 21
State machine configuration:
• key (useful to reference
parent/children state)
• context
• state chart: state nodes &
transitions
• Entry state
const appMachineConfig = {
key: 'app’,
context: initialAppContext,
states: {
browsing: {
...
},
selecting: {
...
},
deleting: {
...
},
prompting: {
...
}
},
initial: 'deleting’,
}
Global State Chart - State Transitions
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart - State Transitions
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart - State Transitions
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState – State Transitions 25
selecting: {
on: {
SELECT_ITEM: {
// implicit transition (no target)
actions: 'addItemToSelection’
},
DESELECT_ITEM: [{
target: 'browsing’,
cond: (ctx: IAppContext) =>( ctx.selectedItems.length === 1)
// condition: last item in selection
actions: 'removeItemFromSelection’,
}, {
// implicit transition (no target)
cond: (ctx: IAppContext) =>( ctx.selectedItems.length > 1)
// condition: still more items selected
actions: 'removeItemFromSelection’,
}],
RESET_SELECTION: {
target: 'browsing’,
actions: 'resetSelection’
},
DELETE_SELECTION: {
target: 'deleting’,
}
}
},
Selecting
DESELECT_ITEM
(if selectedItems.length <=
0)
RESET_SELECTION
DESELECT_ITEM
(if selectedItems.length > 0)
SELECT_ITEM
DELETE_SELECTION
xState – Actions 26
Actions are fire and forget
side effects triggered upon
state machine transitions
• Three types of actions:
• Entry: executed upon
entering a state
• Exit: executed upon
exiting a state
• Transition: executed
when a transition is
triggered by an event
states: {
browsing: {
onEntry: ['loadItems', 'triggerAnalytics’],
onExit: 'triggerAnalytics’,
on: {
SELECT_ITEM: {
target: 'selecting’,
actions: 'addItemToSelection’
},
SELECT_ALL_ITEMS: {
target: 'selecting’,
actions: 'addAllItemsToSelection’
}
}
},
selecting: {...},
deleting: {...},
prompting: {...}
}
xState – Context 27
• Contains quantitative
data (strings, numbers,
objects, etc.)
• Represents the
“extended state”
managed by the
machine
• Used to hydrate the
application components
• Updated using actions
const initialAppContext: IAppContext = {
items: initialAppContextItems,
selectedItems: []
}
const initialAppContextItems = [{
id: 0,
title: 'Summer Photos’,
owner: 'Anthony Stevens’,
updatedAt: new Date(Date.UTC(2017,6,12))
},
...
]
xState – Updating the context 28
const appMachineOptions = {
actions: {
addItemToSelection: assign((ctx, event) => ({
selectedItems: ctx.selectedItems.concat(event.item)
})),
removeItemFromSelection: assign((ctx, event) => ({
selectedItems: ctx.selectedItems.filter(item => item.id !== event.item.id)
})),
resetSelection: assign((_) => ({
selectedItems: []
})),
deleteSelection: assign(ctx => ({
items: ctx.items.filter(item =>
ctx.selectedItems.findIndex(selectedItem =>
selectedItem.id === item.id) < 0
),
selectedItems: []
})),
}
};
Async Pattern
Global State Chart – Asynchronous Calls
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart - Asynchronous Calls
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState – Asynchronous calls (invoke) 32
For asynchronous calls, xState relies on Promises
• onDone transition is invoked when
the promise resolve()
• onError transition is invoked if the
promise reject()
xState + React
https://codesandbox.io/s/k06kloqzyo
https://github.com/xlozinguez/xstate-demo
Hook xState machine to React
Using the official useMachine hook from @xstate/react
https://github.com/davidkpiano/xstate/tree/master/packages/xstate-
react#readme
xState – Matching state 35
xState – Matching state 36
current.matches(’…’) provides the
ability to set conditional statement
against the machine state.
xState – Matching state 37
=> current.matches(’browsing’) => current.matches(’selecting’)
xState – Triggering State Transitions 38
Transitions are triggered by sending an event to the machine using send({…})
Transitions can also be
triggered using the
Machine.transition({…})
method which requires the
state to transition.
Conclusion
A few take away
Pros Cons
• Self documented and captures the
complete picture
• Explicit and easy to understand
thanks to state charts
• Behavior can be tested independently
from presentation layer
• State charts scale very well due to
their inherent composability
• Can accommodate complex use
cases (services, compound vs
parallel, etc.)
• New paradigm to consider
• Requires a complete picture of the
system so it can be transcribed into
state charts
• Uncovers a different set of problem to
solve around state composition (state vs
context, sub-states)
Thank you!
Questions?
References
• https://github.com/davidkpiano/xstate
• https://xstate.js.org
• https://statecharts.github.io
• https://spectrum.chat/statecharts
• https://medium.com/@DavidKPiano/the-facetime-bug-and-the-dangers-of-
implicit-state-machines-a5f0f61bdaa2
• https://www.slideshare.net/lmatteis/statecharts-controlling-the-behavior-of-
complex-systems
• David Khourshid - Infinitely Better UIs with Finite Automata - Slides
Stay in touch:
• xavier.lozinguez@jet.com
• @xlozinguez (Github, Twitter)
• http://xavier.lozinguez.com
Example Code:
• https://codesandbox.io/s/k06kloqzyo
• https://github.com/xlozinguez/xstate-demo

More Related Content

What's hot

[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...Shengyou Fan
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Nelson Glauber Leal
 
Component interface
Component interfaceComponent interface
Component interfaceJAYAARC
 
Spring Data JPAによるデータアクセス徹底入門 #jsug
Spring Data JPAによるデータアクセス徹底入門 #jsugSpring Data JPAによるデータアクセス徹底入門 #jsug
Spring Data JPAによるデータアクセス徹底入門 #jsugMasatoshi Tada
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 
Jetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidJetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidNelson Glauber Leal
 
これで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetup
これで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetupこれで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetup
これで怖くない!?コードリーディングで学ぶSpring Security #中央線MeetupMasatoshi Tada
 
Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase TypesystemSebastian Zarnekow
 
Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Tom Brander
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 
Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 

What's hot (20)

[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Hibernate
Hibernate Hibernate
Hibernate
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021
 
Component interface
Component interfaceComponent interface
Component interface
 
Spring Data JPAによるデータアクセス徹底入門 #jsug
Spring Data JPAによるデータアクセス徹底入門 #jsugSpring Data JPAによるデータアクセス徹底入門 #jsug
Spring Data JPAによるデータアクセス徹底入門 #jsug
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Jetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidJetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no Android
 
Javascript
JavascriptJavascript
Javascript
 
これで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetup
これで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetupこれで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetup
これで怖くない!?コードリーディングで学ぶSpring Security #中央線Meetup
 
React and redux
React and reduxReact and redux
React and redux
 
Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase Typesystem
 
Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Django, What is it, Why is it cool?
Django, What is it, Why is it cool?
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
React Hooks
React HooksReact Hooks
React Hooks
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Threads V4
Threads  V4Threads  V4
Threads V4
 

Similar to Managing Complex UI using xState

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
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologistyoavrubin
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyMartin Zapletal
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Tracy Lee
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design PatternsLidan Hifi
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Chris Alfano
 
Simplified Android Development with Simple-Stack
Simplified Android Development with Simple-StackSimplified Android Development with Simple-Stack
Simplified Android Development with Simple-StackGabor Varadi
 
Size Classes
Size ClassesSize Classes
Size ClassesMarat S
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsGabor Varadi
 
Immutable Libraries for React
Immutable Libraries for ReactImmutable Libraries for React
Immutable Libraries for Reactstbaechler
 
Event Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BEEvent Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BEAndrzej Ludwikowski
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Chris Adamson
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoofelixtrepanier
 

Similar to Managing Complex UI using xState (20)

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
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologist
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data Efficiently
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
 
Flutter
FlutterFlutter
Flutter
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design Patterns
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
 
Simplified Android Development with Simple-Stack
Simplified Android Development with Simple-StackSimplified Android Development with Simple-Stack
Simplified Android Development with Simple-Stack
 
Size Classes
Size ClassesSize Classes
Size Classes
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack Components
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
Om nom nom nom
Om nom nom nomOm nom nom nom
Om nom nom nom
 
Immutable Libraries for React
Immutable Libraries for ReactImmutable Libraries for React
Immutable Libraries for React
 
Event Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BEEvent Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BE
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 

Recently uploaded

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 

Recently uploaded (20)

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 

Managing Complex UI using xState

  • 1. Managing Complex UI with xState
  • 2. Xavier “X” Lozinguez Staff Software Engineer @ Jet Customer Experience Team (Batman) • French • PADI Certified Scuba Diver • BJJ student Contact • xavier.lozinguez@jet.com • @xlozinguez (Github, Twitter) • http://xavier.lozinguez.com
  • 3. Agenda • State Machine? State Charts? • Example of a “complex” UI • xState overview • xState + React • Q&A
  • 5. Finite State Machine – ex: traffic light • Finite amount of states • Predetermined sequenced transitions Green Red Yellow TIME R TIME R TIME R • Events triggers transitions
  • 6. State Chart created by David Harel in 1987 A state chart is a state machine composed of other state machines called sub-states. Sub-states can be state charts themselves (compound states) or remain atomic. Allow for advanced state composition using hierarchical, historic and parallel states.
  • 7. State Chart – ex: traffic light Green Yellow TIME R TIME R TIME R Red
  • 8. State Chart – ex: traffic light Green Yellow TIME R TIME R TIME R Wal k Wai t Sto p PED_TIM ER PED_TIM ER Red
  • 9. Okay… but why? 9 • Tried-and-true methodology for modeling applications • Makes the impossible impossible • Allow for application logic visualization
  • 11. Complex UI example Source: https://material.io/design/interaction/selection.html#item-
  • 14. Global State Chart – Browsing & Selecting Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) SELECT_ITEM RESET_SELECTION What about DELETE_SELECTION? DESELECT_ITEM (if selectedItems.length > 0)
  • 15. Global State Chart – Deleting & Prompting Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 17. xState by David Khourshid (davidkpiano)
  • 18. Global State Chart – Events Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 19. Global State Chart – Events Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 20. xState – Events 20 Composed of a type and an optional payload Payload is then handed over to actions for side-effect purpose Events cause a state machine to transition from its current state to the next type IAppEvent = | { type: 'SELECT_ITEM', item } | { type: 'SELECT_ALL_ITEMS’ } | { type: 'DESELECT_ITEM', item } | { type: 'DELETE_SELECTION’ } | { type: 'SELECTION_DELETED’ } | { type: 'RESET_SELECTION’ } | { type: 'DISMISS_PROMPT' };
  • 21. xState: Machine Configuration 21 State machine configuration: • key (useful to reference parent/children state) • context • state chart: state nodes & transitions • Entry state const appMachineConfig = { key: 'app’, context: initialAppContext, states: { browsing: { ... }, selecting: { ... }, deleting: { ... }, prompting: { ... } }, initial: 'deleting’, }
  • 22. Global State Chart - State Transitions Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 23. Global State Chart - State Transitions Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 24. Global State Chart - State Transitions Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 25. xState – State Transitions 25 selecting: { on: { SELECT_ITEM: { // implicit transition (no target) actions: 'addItemToSelection’ }, DESELECT_ITEM: [{ target: 'browsing’, cond: (ctx: IAppContext) =>( ctx.selectedItems.length === 1) // condition: last item in selection actions: 'removeItemFromSelection’, }, { // implicit transition (no target) cond: (ctx: IAppContext) =>( ctx.selectedItems.length > 1) // condition: still more items selected actions: 'removeItemFromSelection’, }], RESET_SELECTION: { target: 'browsing’, actions: 'resetSelection’ }, DELETE_SELECTION: { target: 'deleting’, } } }, Selecting DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION DESELECT_ITEM (if selectedItems.length > 0) SELECT_ITEM DELETE_SELECTION
  • 26. xState – Actions 26 Actions are fire and forget side effects triggered upon state machine transitions • Three types of actions: • Entry: executed upon entering a state • Exit: executed upon exiting a state • Transition: executed when a transition is triggered by an event states: { browsing: { onEntry: ['loadItems', 'triggerAnalytics’], onExit: 'triggerAnalytics’, on: { SELECT_ITEM: { target: 'selecting’, actions: 'addItemToSelection’ }, SELECT_ALL_ITEMS: { target: 'selecting’, actions: 'addAllItemsToSelection’ } } }, selecting: {...}, deleting: {...}, prompting: {...} }
  • 27. xState – Context 27 • Contains quantitative data (strings, numbers, objects, etc.) • Represents the “extended state” managed by the machine • Used to hydrate the application components • Updated using actions const initialAppContext: IAppContext = { items: initialAppContextItems, selectedItems: [] } const initialAppContextItems = [{ id: 0, title: 'Summer Photos’, owner: 'Anthony Stevens’, updatedAt: new Date(Date.UTC(2017,6,12)) }, ... ]
  • 28. xState – Updating the context 28 const appMachineOptions = { actions: { addItemToSelection: assign((ctx, event) => ({ selectedItems: ctx.selectedItems.concat(event.item) })), removeItemFromSelection: assign((ctx, event) => ({ selectedItems: ctx.selectedItems.filter(item => item.id !== event.item.id) })), resetSelection: assign((_) => ({ selectedItems: [] })), deleteSelection: assign(ctx => ({ items: ctx.items.filter(item => ctx.selectedItems.findIndex(selectedItem => selectedItem.id === item.id) < 0 ), selectedItems: [] })), } };
  • 30. Global State Chart – Asynchronous Calls Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 31. Global State Chart - Asynchronous Calls Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 32. xState – Asynchronous calls (invoke) 32 For asynchronous calls, xState relies on Promises • onDone transition is invoked when the promise resolve() • onError transition is invoked if the promise reject()
  • 34. Hook xState machine to React Using the official useMachine hook from @xstate/react https://github.com/davidkpiano/xstate/tree/master/packages/xstate- react#readme
  • 36. xState – Matching state 36 current.matches(’…’) provides the ability to set conditional statement against the machine state.
  • 37. xState – Matching state 37 => current.matches(’browsing’) => current.matches(’selecting’)
  • 38. xState – Triggering State Transitions 38 Transitions are triggered by sending an event to the machine using send({…}) Transitions can also be triggered using the Machine.transition({…}) method which requires the state to transition.
  • 40. A few take away Pros Cons • Self documented and captures the complete picture • Explicit and easy to understand thanks to state charts • Behavior can be tested independently from presentation layer • State charts scale very well due to their inherent composability • Can accommodate complex use cases (services, compound vs parallel, etc.) • New paradigm to consider • Requires a complete picture of the system so it can be transcribed into state charts • Uncovers a different set of problem to solve around state composition (state vs context, sub-states)
  • 42. References • https://github.com/davidkpiano/xstate • https://xstate.js.org • https://statecharts.github.io • https://spectrum.chat/statecharts • https://medium.com/@DavidKPiano/the-facetime-bug-and-the-dangers-of- implicit-state-machines-a5f0f61bdaa2 • https://www.slideshare.net/lmatteis/statecharts-controlling-the-behavior-of- complex-systems • David Khourshid - Infinitely Better UIs with Finite Automata - Slides
  • 43. Stay in touch: • xavier.lozinguez@jet.com • @xlozinguez (Github, Twitter) • http://xavier.lozinguez.com Example Code: • https://codesandbox.io/s/k06kloqzyo • https://github.com/xlozinguez/xstate-demo

Editor's Notes

  1. A state machine is a finite set of states that can transition to each other deterministically due to events - The term state used within the statechart formalism simply describes a textual label which drives our program in understanding what needs to happen. - To the contrary, in the React world the term state usually describes some data that we use to render our components. ------ Finite amount of states between which the machine transition in a predetermined sequence using events.
  2. A state machine is a finite set of states that can transition to each other deterministically due to events - The term state used within the statechart formalism simply describes a textual label which drives our program in understanding what needs to happen. - To the contrary, in the React world the term state usually describes some data that we use to render our components.
  3. A state machine is a finite set of states that can transition to each other deterministically due to events - The term state used within the statechart formalism simply describes a textual label which drives our program in understanding what needs to happen. - To the contrary, in the React world the term state usually describes some data that we use to render our components.
  4. While finite states are well-defined in finite state machines and statecharts, state that represents quantitative data (e.g., arbitrary strings, numbers, objects, etc.) that can be potentially infinite is represented as extended state instead
  5. Recommended rules: Never mutate the context, use assign({ … }) to preserve state history Never mutate the context externally Unit Test your actions!
  6. Machines can talk to each other using the `invoke` method https://xstate.js.org/docs/guides/communication.html
  7. By modeling the UI logic as a statechart, not only do you have full visibility into all edge cases, but adding/removing/modifying features becomes much easier and less bug-prone, since you instantly know all parts of your UI logic that feature will affect.