SlideShare a Scribd company logo
From User Action to
Framework Reaction
Reactivity in modern Frontend Frameworks
Jonas Bandi
jonas.bandi@ivorycode.com
Twitter: @jbandi
- Freelancer, in den letzten 6 Jahren vor allem in Projekten
im Spannungsfeld zwischen modernen Webentwicklung
und traditionellen Geschäftsanwendungen.
- Dozent an der Berner Fachhochschule seit 2007
- In-House Kurse:Web-Technologien im Enterprise
UBS, Postfinance, Mobiliar, SBB, BIT, BSI, Elca ...
JavaScript / Angular / React / Vue.js
Schulung / Beratung / Coaching / Reviews
jonas.bandi@ivorycode.com
http://ivorycode.com/#schulung
Agenda
Intro
Baseline:
"Out of the Box"-Reactivity of , and
(Slides and Demos)
Further Explorations:
Demos and Code Explorations
https://github.com/jbandi/framework-reactivity
Reactivity ?
Reactive Programming?
In computing, reactive programming is a declarative
programming paradigm concerned with data
streams and the propagation of change.
- Wikipedia
Reactive programming is programming
with asynchronous data streams.
Andre Staltz
The introduction to Reactive Programming you've been missing
https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
click$	
		.pipe(scan(count	=>	count	+	1,	0))	
		.subscribe(count	=>	console.log(`Clicked	${count}	times`));
From User Action to Framework Reaction
In the Beginning there
was Darkness ...
... then the DOM was created.
... and we manipulated
the DOM ...
$(".menu-item")	
.removeClass("active")	
.addClass("inactive	")	
.css("padding-left",	"0px")	
.find(".trigger")	
.click(function(ev)	{	
			//	spaghetti	carbonara?	
})	
.each(function	()	{	
		 //	spaghetti	napoli?	
});
... the Dark Ages of DOM ...
... a new hope ...
Model View Controller
Client Side MVC
HTML
Brow
ser
Model:
POJOs
Controller
View
DOM
Server
initial load
AJAX
Thou shalt not manipulate
the DOM!
the DOM *is* updated
State is Managed in JavaScript
Action:
change
state
Reaction:
re-render
Dom
Ajax
Timeout
...
User
t
r
i
g
g
e
r
State
Reactivity:The framework reacts on state
changes and updates the UI.
DOM
UI
EvanYou - Reactivity in Frontend JavaScript Frameworks: https://www.youtube.com/watch?v=r4pNEdIt_l4
http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
Reactivity:What and Why?
Traditional
"DOM-centric"
applications
UI = state
Browsers have "built-in" reactivity: If the DOM is
changed, the UI is re-rendered.
UI = f(state)
With modern SPA
architectures (MVC,
MVP, Components …) the
client state is
represented as
JavaScript objects.
The UI that you can see and manipulate
on screen is the result of painting a
visual representation of data.
Reactive programming in general addresses the question: How to
deal with change over time?
The UI should (automatically) re-render when the state changes.
When to call?
https://blog.danlew.net/2017/07/27/an-introduction-to-functional-reactive-programming/
https://twitter.com/Rich_Harris/status/1058751085706383362
Baseline: Core Reactivity
Zone.js
Change	
Detection
Angular Default Reactivity
@Component({	
		selector:	'app-counter',	
		template:	`	
				<div>	
						{{count}}	
				</div>	
		`	
})	
export	class	CounterComponent	implements	OnInit	{	
		count	=	0;	
		ngOnInit()	{	
				setInterval(()	=>	{	this.count++;	},	1000);	
		}	
}
Zone.js:
The "Magic" in Angular Change Detection
Zone.js is a JavaScript library provided by the Angular project that
patches many asynchronous browser APIs. Listeners can then be
triggered when these APIs are executed.
Angular relies on Zone.js to trigger automatic change detection.
Angular is running inside the NgZone (a zone created via
Zone.js).When async APIs are executed Angular gets notified
when the execution has finished and triggers change detection.
https://github.com/angular/zone.js/
https://medium.com/better-programming/zone-js-for-angular-devs-573d89bbb890
Patched APIs (examples): setTimeout, Promise, XMLHttpRequest, prompt
and DOM events.
More details: https://github.com/angular/angular/blob/master/packages/zone.js/STANDARD-APIS.md
Default Reactivity in Angular
UI = f(state)
Triggered by Zone.js
"simulated reactivity"
setInterval(	
1000);
Zone.js
"Zone to Angular":
Hey, there might be something going on ...
apply minimal
changes.
DOM
()	=>	this.count++
State
count:	42
let's check
everything ...
increase
<div>42</div>
change
detection
"simulated reactivity"
Default Change Detection
As default Angular detects changes by inspecting the state of all
components every time change detection is triggered.
Component
Component Component
Component Component
event
trigger change detection
on app
propagate change
detection to
children
propagate change
detection to
children
CD
CD
CD
CD
CD
Change detection is always
triggered at the top of the
component hirarchy and
propagates down to each child.
Every value used in a template
is inspected and compared to
the previous value.
Zone.js Checking all components
on every possible event can
be performance intense.
Default Reactivity in Angular
Zone.js with Default Change Detection:
• are a form of simulated reactivity: the framework
does not react to changes but to events that might
potentially resulted in changes
• are a form of transparent reactivity: It makes
reactivity an implicit characteristic of your program.
TheTaxonomy of Reactive Programming: https://vsavkin.com/the-taxonomy-of-reactive-programming-d40e2e23dee4
https://github.com/meteor/docs/blob/version-NEXT/long-form/tracker-manual.md
A common alternative in Angular is to model Reactivity
explicitly with RxJS, this is a form of explicit reactivity.
Default Angular Reactivity
Transparent Reactivity:
The programmer should be
able to use ideomatic
JavaScript, the Framework
does the rest.
Strength Weakness
Zone.js: Patching the browser is
problematic on many levels.
Brute-force approach of default
change detection is not optimal in
regard to performance.
Change Detection imposes
constraints ...
- avoid setter/getters
- unidirectional data-flow
- avoid async/await
"Simulated Reactivity"
Unidirectional Data Flow
Angular enforces unidirectional data flow from top to
bottom of the component tree.
• A child is not allowed to change the state of the parent once
the parent changes have been processed.
• This prevents cycles in the change detection.
(to prevent inconsistencies between state and ui and for better
performance)
• In development mode Angular performs a check (a second
change detection) to ensure that the component tree has
not changed after change detection. If there are changes it
throws a
ExpressionChangedAfterItHasBeenCheckedError.
https://indepth.dev/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error/
(Missing?) Reactivity in React
Function Components
function	AppComponent(props)	{	
return	(	
				<div>	
								<h1>{props.title}</h1>	
								<p>{props.message}</p>	
				</div>	
);	
}
properties
A components is a plain JavaScript function.
UI
(DOM ... )
The function is called each time the UI is
renedered (i.e. with every data-change)
A component transforms JavaScript state into the DOM structure:
UI = f(state)
import	React,	{	useEffect,	useState	}	from	'react';	
export	function	Counter()	{	
				const	[count,	setCount]	=	useState(0);	
				useEffect(()	=>	{	
								setInterval(()	=>	{	
												setCount(count	=>	count	+	1);	
								},	1000)	
				},	[]);	
				return	<div>{count}</div>	
}
React is used
to manage the
state
Reactivity in React
UI = f(state) triggered by
the programmer
setInterval(()	=>	
1000);
Programmer to React:
"Please change the state for me ... "
apply minimal changes.
DOM
setCount(count	=>	count	+	1),
State
count:	42
update the state
<div>42</div>
trigger re-rendering
virtual
DOM
From User Action to Framework Reaction
React Reactivity
Functional Mindset:
- Rendering is a side-effect
of state changes.
- Components transform
state to ui.
Strength Weakness
"Render everything approach" is
wasteful.
State is managed by React: we
have to use the APIs and concepts
of React.
"Everything is rendered on every state change"
Reactive State in Vue
import	{	reactive,	watch	}	from	'vue'	
const	state	=	reactive({	
		count:	0	
})	
watch(()	=>	{	
		document.body.innerHTML	=	`count	is	${state.count}`	
})	
setInterval(()	=>	state.count++,	1000);
The example is using the composition API of upcoming vue 3:
https://vue-composition-api-rfc.netlify.com/
This is available inVue 2: https://github.com/vuejs/composition-api
changing state triggers re-rendering
Reactivity inVue
UI = f(state) triggered by
reactive state
setInterval(	
()	=>	state.count++,	
1000);
apply minimal changes.
DOM
State (Vue proxy)
{	count:	42	}
<div>42</div>
trigger re-rendering
get/set	count()
increase
ChangeTracking & Reactive State
https://vuejs.org/v2/guide/reactivity.html
Vue Reactivity
"True Reactivity":The state
can be observed.
Strength Weakness
State is not "plain" JavaScript, which
comes with its own limitations.
"Reactive State"
Alternatives &Variations
Zone.js
Change	
Detection
OnPush
Observables
Zone-Less
Angular Reactivity Options
Observables & async Pipe
UI$ = f(state$)
UI = f(state)
Reactivity realized with Streams
Triggered by Zone.js
"streams: true reactive programming"
"simulated reactivity"
Computed State
Anything that can be derived from the
application state, should be derived.
Automatically.
- MobX Introduction
No ideomatic
solution:
- getters/setters
- ngOnChanges
- Pure Pipe
- Observables
- (NgRx)
Derived state is
calculated during
rendering.
Optmization
with
Memoization.
Computed
properties.
State outside Components
Application-
State
Component
Tree
change
render
Application
A state container extracts the shared state out of the
components, and manages it in a global singleton.
The component tree becomes a big "view", any
component can access the state or trigger changes, no
matter where they are in the tree!
store
Code: https://github.com/jbandi/framework-reactivity
Have Fun with the
Framework of your Choice!
Twitter: @jbandi
Resources
• TheTaxonomy of Reactive Programming
https://vsavkin.com/the-taxonomy-of-reactive-programming-d40e2e23dee4
• Front end development and change detection (Angular vs. React):
https://www.youtube.com/watch?v=1i8klHov3vA
• JS Roundabout, Reactivity in React andVue, February 2018
https://www.youtube.com/watch?v=HWZq_rlJU4o
• Why React Is *Not* Reactive - Shawn Wang @ ReactNYC
https://www.youtube.com/watch?v=ZZoB5frlcnE
• Shift Dev 2019: "Rethinking Reactivity" - Rich Harris (NewYorkTimes)
https://www.youtube.com/watch?v=gJ2P6hGwcgo
• The Return of 'Write Less, Do More' by Rich Harris | JSCAMP 2019
https://www.youtube.com/watch?v=BzX4aTRPzno
• Reactivity:Vue 2 vsVue 3
https://www.vuemastery.com/blog/Reactivity-Vue2-vs-Vue3/

More Related Content

What's hot (20)

DOCX
Angular Interview Questions & Answers
Ratnala Charan kumar
 
PPTX
Javascript
Sun Technlogies
 
PPTX
Java script session 3
Saif Ullah Dar
 
PPT
Node.js an introduction
Meraj Khattak
 
PDF
Metaprogramming JavaScript
danwrong
 
DOCX
Javascript tutorial
Abhishek Kesharwani
 
PPT
Javascript by geetanjali
Geetanjali Bhosale
 
PPTX
Javascript
Nagarajan
 
PDF
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
PDF
Introduction to Javascript programming
Fulvio Corno
 
PDF
Html5 Interview Questions & Answers
Ratnala Charan kumar
 
ODP
Introduction to Knockout Js
Knoldus Inc.
 
PPT
Java Script ppt
Priya Goyal
 
PPT
Javascript
Mallikarjuna G D
 
PPTX
Introduction to Javascript By Satyen
Satyen Pandya
 
PPTX
Java script Session No 1
Saif Ullah Dar
 
PPTX
Introduction to JavaScript Programming
Raveendra R
 
PPT
8 Most Effective Node.js Tools for Developers
iMOBDEV Technologies Pvt. Ltd.
 
PPTX
Java Script An Introduction By HWA
Emma Wood
 
Angular Interview Questions & Answers
Ratnala Charan kumar
 
Javascript
Sun Technlogies
 
Java script session 3
Saif Ullah Dar
 
Node.js an introduction
Meraj Khattak
 
Metaprogramming JavaScript
danwrong
 
Javascript tutorial
Abhishek Kesharwani
 
Javascript by geetanjali
Geetanjali Bhosale
 
Javascript
Nagarajan
 
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Introduction to Javascript programming
Fulvio Corno
 
Html5 Interview Questions & Answers
Ratnala Charan kumar
 
Introduction to Knockout Js
Knoldus Inc.
 
Java Script ppt
Priya Goyal
 
Javascript
Mallikarjuna G D
 
Introduction to Javascript By Satyen
Satyen Pandya
 
Java script Session No 1
Saif Ullah Dar
 
Introduction to JavaScript Programming
Raveendra R
 
8 Most Effective Node.js Tools for Developers
iMOBDEV Technologies Pvt. Ltd.
 
Java Script An Introduction By HWA
Emma Wood
 

Similar to From User Action to Framework Reaction (20)

PDF
From User Action to Framework Reaction
jbandi
 
PDF
Reactive programming with RxJS - Taiwan
modernweb
 
PPTX
Functional reactive programming
Ahmed Kamel Taha
 
PDF
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
PDF
Predictable reactive state management - ngrx
Ilia Idakiev
 
PDF
Functional Reactive Programming in JavaScript
zupzup.org
 
ODP
Appstate
Tomas Kulich
 
PDF
Moving towards Reactive Programming
Deepak Shevani
 
PDF
Reactive programming and RxJS
Ravi Mone
 
PDF
Concepts of React
inovex GmbH
 
PDF
Functional Reactive Programming. What does it solve? Does it solve things? Le...
Netta Bondy
 
PDF
[DevDay 2019] Reactive Programming with JavaScript - By Pham Nguyen Duc, Web ...
DevDay Da Nang
 
PDF
I have a stream - Insights in Reactive Programming - Jan Carsten Lohmuller - ...
Codemotion
 
PPTX
Functional Reactive Programming with RxJS
stefanmayer13
 
PPTX
Intro to RxJS
Alan Fadliawan
 
PDF
Reactive Programming in the Browser feat. Scala.js and Rx
Luka Jacobowitz
 
PPTX
Reactive programming
saykopatt
 
PPTX
Reactive programming every day
Vadym Khondar
 
PDF
JS Experience 2017 - Reactive Interfaces com React & RxJS
iMasters
 
PPTX
Angular Frankfurt #1 - Managing Application State in Reactive Angular Applica...
Florian Reifschneider
 
From User Action to Framework Reaction
jbandi
 
Reactive programming with RxJS - Taiwan
modernweb
 
Functional reactive programming
Ahmed Kamel Taha
 
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
Predictable reactive state management - ngrx
Ilia Idakiev
 
Functional Reactive Programming in JavaScript
zupzup.org
 
Appstate
Tomas Kulich
 
Moving towards Reactive Programming
Deepak Shevani
 
Reactive programming and RxJS
Ravi Mone
 
Concepts of React
inovex GmbH
 
Functional Reactive Programming. What does it solve? Does it solve things? Le...
Netta Bondy
 
[DevDay 2019] Reactive Programming with JavaScript - By Pham Nguyen Duc, Web ...
DevDay Da Nang
 
I have a stream - Insights in Reactive Programming - Jan Carsten Lohmuller - ...
Codemotion
 
Functional Reactive Programming with RxJS
stefanmayer13
 
Intro to RxJS
Alan Fadliawan
 
Reactive Programming in the Browser feat. Scala.js and Rx
Luka Jacobowitz
 
Reactive programming
saykopatt
 
Reactive programming every day
Vadym Khondar
 
JS Experience 2017 - Reactive Interfaces com React & RxJS
iMasters
 
Angular Frankfurt #1 - Managing Application State in Reactive Angular Applica...
Florian Reifschneider
 
Ad

Recently uploaded (20)

PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Ad

From User Action to Framework Reaction

  • 1. From User Action to Framework Reaction Reactivity in modern Frontend Frameworks
  • 2. Jonas Bandi [email protected] Twitter: @jbandi - Freelancer, in den letzten 6 Jahren vor allem in Projekten im Spannungsfeld zwischen modernen Webentwicklung und traditionellen Geschäftsanwendungen. - Dozent an der Berner Fachhochschule seit 2007 - In-House Kurse:Web-Technologien im Enterprise UBS, Postfinance, Mobiliar, SBB, BIT, BSI, Elca ... JavaScript / Angular / React / Vue.js Schulung / Beratung / Coaching / Reviews [email protected] http://ivorycode.com/#schulung
  • 3. Agenda Intro Baseline: "Out of the Box"-Reactivity of , and (Slides and Demos) Further Explorations: Demos and Code Explorations https://github.com/jbandi/framework-reactivity
  • 5. Reactive Programming? In computing, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change. - Wikipedia Reactive programming is programming with asynchronous data streams. Andre Staltz The introduction to Reactive Programming you've been missing https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 click$ .pipe(scan(count => count + 1, 0)) .subscribe(count => console.log(`Clicked ${count} times`));
  • 7. In the Beginning there was Darkness ...
  • 8. ... then the DOM was created.
  • 9. ... and we manipulated the DOM ... $(".menu-item") .removeClass("active") .addClass("inactive ") .css("padding-left", "0px") .find(".trigger") .click(function(ev) { // spaghetti carbonara? }) .each(function () { // spaghetti napoli? });
  • 10. ... the Dark Ages of DOM ...
  • 11. ... a new hope ...
  • 14. Thou shalt not manipulate the DOM!
  • 15. the DOM *is* updated
  • 16. State is Managed in JavaScript Action: change state Reaction: re-render Dom Ajax Timeout ... User t r i g g e r State Reactivity:The framework reacts on state changes and updates the UI. DOM UI EvanYou - Reactivity in Frontend JavaScript Frameworks: https://www.youtube.com/watch?v=r4pNEdIt_l4 http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
  • 17. Reactivity:What and Why? Traditional "DOM-centric" applications UI = state Browsers have "built-in" reactivity: If the DOM is changed, the UI is re-rendered. UI = f(state) With modern SPA architectures (MVC, MVP, Components …) the client state is represented as JavaScript objects. The UI that you can see and manipulate on screen is the result of painting a visual representation of data. Reactive programming in general addresses the question: How to deal with change over time? The UI should (automatically) re-render when the state changes. When to call? https://blog.danlew.net/2017/07/27/an-introduction-to-functional-reactive-programming/
  • 22. Zone.js: The "Magic" in Angular Change Detection Zone.js is a JavaScript library provided by the Angular project that patches many asynchronous browser APIs. Listeners can then be triggered when these APIs are executed. Angular relies on Zone.js to trigger automatic change detection. Angular is running inside the NgZone (a zone created via Zone.js).When async APIs are executed Angular gets notified when the execution has finished and triggers change detection. https://github.com/angular/zone.js/ https://medium.com/better-programming/zone-js-for-angular-devs-573d89bbb890 Patched APIs (examples): setTimeout, Promise, XMLHttpRequest, prompt and DOM events. More details: https://github.com/angular/angular/blob/master/packages/zone.js/STANDARD-APIS.md
  • 23. Default Reactivity in Angular UI = f(state) Triggered by Zone.js "simulated reactivity" setInterval( 1000); Zone.js "Zone to Angular": Hey, there might be something going on ... apply minimal changes. DOM () => this.count++ State count: 42 let's check everything ... increase <div>42</div> change detection "simulated reactivity"
  • 24. Default Change Detection As default Angular detects changes by inspecting the state of all components every time change detection is triggered. Component Component Component Component Component event trigger change detection on app propagate change detection to children propagate change detection to children CD CD CD CD CD Change detection is always triggered at the top of the component hirarchy and propagates down to each child. Every value used in a template is inspected and compared to the previous value. Zone.js Checking all components on every possible event can be performance intense.
  • 25. Default Reactivity in Angular Zone.js with Default Change Detection: • are a form of simulated reactivity: the framework does not react to changes but to events that might potentially resulted in changes • are a form of transparent reactivity: It makes reactivity an implicit characteristic of your program. TheTaxonomy of Reactive Programming: https://vsavkin.com/the-taxonomy-of-reactive-programming-d40e2e23dee4 https://github.com/meteor/docs/blob/version-NEXT/long-form/tracker-manual.md A common alternative in Angular is to model Reactivity explicitly with RxJS, this is a form of explicit reactivity.
  • 26. Default Angular Reactivity Transparent Reactivity: The programmer should be able to use ideomatic JavaScript, the Framework does the rest. Strength Weakness Zone.js: Patching the browser is problematic on many levels. Brute-force approach of default change detection is not optimal in regard to performance. Change Detection imposes constraints ... - avoid setter/getters - unidirectional data-flow - avoid async/await "Simulated Reactivity"
  • 27. Unidirectional Data Flow Angular enforces unidirectional data flow from top to bottom of the component tree. • A child is not allowed to change the state of the parent once the parent changes have been processed. • This prevents cycles in the change detection. (to prevent inconsistencies between state and ui and for better performance) • In development mode Angular performs a check (a second change detection) to ensure that the component tree has not changed after change detection. If there are changes it throws a ExpressionChangedAfterItHasBeenCheckedError. https://indepth.dev/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error/
  • 29. Function Components function AppComponent(props) { return ( <div> <h1>{props.title}</h1> <p>{props.message}</p> </div> ); } properties A components is a plain JavaScript function. UI (DOM ... ) The function is called each time the UI is renedered (i.e. with every data-change) A component transforms JavaScript state into the DOM structure: UI = f(state)
  • 31. Reactivity in React UI = f(state) triggered by the programmer setInterval(() => 1000); Programmer to React: "Please change the state for me ... " apply minimal changes. DOM setCount(count => count + 1), State count: 42 update the state <div>42</div> trigger re-rendering virtual DOM
  • 33. React Reactivity Functional Mindset: - Rendering is a side-effect of state changes. - Components transform state to ui. Strength Weakness "Render everything approach" is wasteful. State is managed by React: we have to use the APIs and concepts of React. "Everything is rendered on every state change"
  • 35. import { reactive, watch } from 'vue' const state = reactive({ count: 0 }) watch(() => { document.body.innerHTML = `count is ${state.count}` }) setInterval(() => state.count++, 1000); The example is using the composition API of upcoming vue 3: https://vue-composition-api-rfc.netlify.com/ This is available inVue 2: https://github.com/vuejs/composition-api changing state triggers re-rendering
  • 36. Reactivity inVue UI = f(state) triggered by reactive state setInterval( () => state.count++, 1000); apply minimal changes. DOM State (Vue proxy) { count: 42 } <div>42</div> trigger re-rendering get/set count() increase
  • 37. ChangeTracking & Reactive State https://vuejs.org/v2/guide/reactivity.html
  • 38. Vue Reactivity "True Reactivity":The state can be observed. Strength Weakness State is not "plain" JavaScript, which comes with its own limitations. "Reactive State"
  • 41. Observables & async Pipe UI$ = f(state$) UI = f(state) Reactivity realized with Streams Triggered by Zone.js "streams: true reactive programming" "simulated reactivity"
  • 42. Computed State Anything that can be derived from the application state, should be derived. Automatically. - MobX Introduction No ideomatic solution: - getters/setters - ngOnChanges - Pure Pipe - Observables - (NgRx) Derived state is calculated during rendering. Optmization with Memoization. Computed properties.
  • 43. State outside Components Application- State Component Tree change render Application A state container extracts the shared state out of the components, and manages it in a global singleton. The component tree becomes a big "view", any component can access the state or trigger changes, no matter where they are in the tree! store
  • 45. Resources • TheTaxonomy of Reactive Programming https://vsavkin.com/the-taxonomy-of-reactive-programming-d40e2e23dee4 • Front end development and change detection (Angular vs. React): https://www.youtube.com/watch?v=1i8klHov3vA • JS Roundabout, Reactivity in React andVue, February 2018 https://www.youtube.com/watch?v=HWZq_rlJU4o • Why React Is *Not* Reactive - Shawn Wang @ ReactNYC https://www.youtube.com/watch?v=ZZoB5frlcnE • Shift Dev 2019: "Rethinking Reactivity" - Rich Harris (NewYorkTimes) https://www.youtube.com/watch?v=gJ2P6hGwcgo • The Return of 'Write Less, Do More' by Rich Harris | JSCAMP 2019 https://www.youtube.com/watch?v=BzX4aTRPzno • Reactivity:Vue 2 vsVue 3 https://www.vuemastery.com/blog/Reactivity-Vue2-vs-Vue3/