SlideShare une entreprise Scribd logo
1  sur  32
React
What is React?
• Client-side library made and open-sourced by Facebook
• Much simpler than Angular (fast learning curve)
• Main goal is to be fast, scalable, and simple
• React Native allows you to port over code to native iOS
or Android apps
Why Would You Use React?
• Fast Learning Curve
• Reusable Components which manage state
• Ability to use JSX which reduces risk of XSS
• Abstraction
o View in MVC as opposed to client-side MVC
o Use Flux/Redux as single source of truth
React Basics – Virtual DOM / Components
• Virtual DOM
o React keeps an abstraction of the DOM; when changes are made, it will only re-render the elements
that were changed, not the entire DOM
o Makes it very fast from a performance perspective
• Components
o React allows you to create your own HTML elements and then define logic and state variables for
these elements
o 2 key methods to know:
o React.Component:
o Allows us to define new Components
o Must have render() method
o ReactDOM.render:
o Lets us place Component in DOM
React Basics - State
• As noted, each Component maintains its own set of
variables which programmer defines
• We can set and get these state variables; when we set
them, it causes the Component to re-render
• We will talk about this more later, when we discuss Redux
React Basics – Events and JSX
• Components have lifecycle methods and event-based
methods that will update state and re-render
• For events (such as onClick or onSubmit), we access value
through event.target.value -> pass this to child components
if necessary, and then update state
• JSX
o React allows you to write HTML-like code mixed with JS to define how to
render or manipulate Components
Components can have state
A complex UI usually introduces
dependencies between
components
Parent -> Child dependencies are
easy
Child -> Parent and Sibling
dependencies are harder
The State Management Problem
The State Management Problem
The Flux Architecture
The Flux Architecture
Library written by Dan Abramov (@gaeron)
Built on a reducer abstraction
Redux: Reducer + Flux
Redux: Reducer + Flux
Reducer
Action
Reducer
Action
State State State
Action
...
Redux: Reducer + Flux
Flux Redux
Update logic in stores Update logic in reducers
Multiple stores Single store, multiple reducers
Multiple state trees Single state atom
Easy state reconstruction
Redux: Reducer + Flux
Redux reducers should be pure functions
This makes testing Redux based code really easy, right?
...But how do we handle side effects?
AJAX calls
Web Sockets
Integrating 3rd party libraries
Side Effects with Redux
New
State
Side Effects with Redux: Middleware
Middleware 1 Middleware 2Action ...
Side effect?
Dispatch action?
Reducer
Store Store
Side effect?
Dispatch action?
Many different solutions exist, variously opinionated
Look at three different middlewares, and their impacts on testing:
redux-thunk (@gaeron)
redux-api-middleware (@agraboso)
redux-saga (@yelouafi)
Standard example: making an API call
Side Effects with Redux: Middleware
Side Effects with Redux: Thunks
Redux-thunk allows action creators to return functions
Those functions can be impure, and also dispatch other actions
Generalised solution to side effects, can be used for API calls
Side Effects with Redux: Thunks
How do we test this? Action creators no longer pure functions
Could mock Redux store and API call?
Middleware that deals only with making API requests.
Many existing examples. Will use “redux-api-middleware” as example.
Side Effects with Redux: API middleware
All API-related side effects isolated in (fully tested!) middleware
Only need to check:
Correct actions are being created
Payload correctly processed
Side Effects with Redux: API middleware
Side Effects with Redux: API middleware
Side Effects with Redux: Sagas
Warning:
Can be overkill for your app
Significant additional abstraction
Additional learning curve
Side Effects with Redux: Sagas
Generators:
May be familiar from other languages (e.g. Python)
Allow function execution to be paused
Allow information to be passed in and out
Side Effects with Redux: Sagas
Side Effects with Redux: Sagas
Side Effects with Redux: Sagas
Question:
So what? Added additional complexity, what have we won?
Answer:
Further decoupling of components
Declarative actions
Complex sequences of effects
Easier testability of those complex sequences
Side Effects with Redux: Sagas
Side Effects with Redux: Sagas
Side Effects with Redux: Sagas
Utilise helper functions from redux-saga for:
Delays
Debouncing
Throttling
Dynamically creating new sagas
Cancelling existing sagas
Summary
Thunks Specific Middleware Sagas
General & flexible Allows building focussed
API
Powerful & flexible
Testing requires mocking Small learning overhead Significant learning
overhead
Logic in action creators Easy testing Easy testing
Suitable for smaller or
simpler apps
Suitable for most apps Suitable for large & complex
apps
Thank You
Elias Malik
elias@foundersandcoders.com
Github: @eliascodes

Contenu connexe

Tendances

Tendances (20)

Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Intro to Flux - ReactJS Warsaw #1
Intro to Flux - ReactJS Warsaw #1Intro to Flux - ReactJS Warsaw #1
Intro to Flux - ReactJS Warsaw #1
 
React js
React jsReact js
React js
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 
Project Report
Project ReportProject Report
Project Report
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6
 
Meetup dpjs react_api
Meetup dpjs react_apiMeetup dpjs react_api
Meetup dpjs react_api
 
Services Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSServices Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJS
 
GraphQL Introduction with Spring Boot
GraphQL Introduction with Spring BootGraphQL Introduction with Spring Boot
GraphQL Introduction with Spring Boot
 
Gatling - Stress test tool
Gatling - Stress test toolGatling - Stress test tool
Gatling - Stress test tool
 
Spring reactor
Spring reactorSpring reactor
Spring reactor
 
Matteo Vaccari - Going Frameworkless in the Backend - Codemotion Milan 2018
Matteo Vaccari - Going Frameworkless in the Backend - Codemotion Milan 2018Matteo Vaccari - Going Frameworkless in the Backend - Codemotion Milan 2018
Matteo Vaccari - Going Frameworkless in the Backend - Codemotion Milan 2018
 
Introducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRIntroducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoR
 
Spring framework 5: New Core and Reactive features
Spring framework 5: New Core and Reactive featuresSpring framework 5: New Core and Reactive features
Spring framework 5: New Core and Reactive features
 
Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!
 
Андрій Рева, "How to build reactive java application"
Андрій Рева, "How to build reactive java application"Андрій Рева, "How to build reactive java application"
Андрій Рева, "How to build reactive java application"
 
Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Workflow as code with Azure Durable Functions
Workflow as code with Azure Durable FunctionsWorkflow as code with Azure Durable Functions
Workflow as code with Azure Durable Functions
 

Similaire à React gsg presentation with ryan jung & elias malik

Introduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptxIntroduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptx
SHAIKIRFAN715544
 
Welcome to React & Flux !
Welcome to React & Flux !Welcome to React & Flux !
Welcome to React & Flux !
Ritesh Kumar
 
Reactjs notes.pptx for web development- tutorial and theory
Reactjs  notes.pptx for web development- tutorial and theoryReactjs  notes.pptx for web development- tutorial and theory
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 

Similaire à React gsg presentation with ryan jung & elias malik (20)

React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
 
JOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and ReduxJOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and Redux
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
A React Journey
A React JourneyA React Journey
A React Journey
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
 
Techpaathshala ReactJS .pdf
Techpaathshala ReactJS .pdfTechpaathshala ReactJS .pdf
Techpaathshala ReactJS .pdf
 
Introduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptxIntroduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptx
 
Welcome to React & Flux !
Welcome to React & Flux !Welcome to React & Flux !
Welcome to React & Flux !
 
Introduction to React JS.pptx
Introduction to React JS.pptxIntroduction to React JS.pptx
Introduction to React JS.pptx
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Reactjs notes.pptx for web development- tutorial and theory
Reactjs  notes.pptx for web development- tutorial and theoryReactjs  notes.pptx for web development- tutorial and theory
Reactjs notes.pptx for web development- tutorial and theory
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
React
ReactReact
React
 
reactJS
reactJSreactJS
reactJS
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
 

Plus de Lama K Banna

Plus de Lama K Banna (20)

The TikTok Masterclass Deck.pdf
The TikTok Masterclass Deck.pdfThe TikTok Masterclass Deck.pdf
The TikTok Masterclass Deck.pdf
 
دليل كتابة المشاريع.pdf
دليل كتابة المشاريع.pdfدليل كتابة المشاريع.pdf
دليل كتابة المشاريع.pdf
 
Investment proposal
Investment proposalInvestment proposal
Investment proposal
 
Funding proposal
Funding proposalFunding proposal
Funding proposal
 
5 incisions
5 incisions5 incisions
5 incisions
 
Lecture 3 facial cosmetic surgery
Lecture 3 facial cosmetic surgery Lecture 3 facial cosmetic surgery
Lecture 3 facial cosmetic surgery
 
lecture 1 facial cosmatic surgery
lecture 1 facial cosmatic surgery lecture 1 facial cosmatic surgery
lecture 1 facial cosmatic surgery
 
Facial neuropathology Maxillofacial Surgery
Facial neuropathology Maxillofacial SurgeryFacial neuropathology Maxillofacial Surgery
Facial neuropathology Maxillofacial Surgery
 
Lecture 2 Facial cosmatic surgery
Lecture 2 Facial cosmatic surgery Lecture 2 Facial cosmatic surgery
Lecture 2 Facial cosmatic surgery
 
Lecture 12 general considerations in treatment of tmd
Lecture 12 general considerations in treatment of tmdLecture 12 general considerations in treatment of tmd
Lecture 12 general considerations in treatment of tmd
 
Lecture 10 temporomandibular joint
Lecture 10 temporomandibular jointLecture 10 temporomandibular joint
Lecture 10 temporomandibular joint
 
Lecture 11 temporomandibular joint Part 3
Lecture 11 temporomandibular joint Part 3Lecture 11 temporomandibular joint Part 3
Lecture 11 temporomandibular joint Part 3
 
Lecture 9 TMJ anatomy examination
Lecture 9 TMJ anatomy examinationLecture 9 TMJ anatomy examination
Lecture 9 TMJ anatomy examination
 
Lecture 7 correction of dentofacial deformities Part 2
Lecture 7 correction of dentofacial deformities Part 2Lecture 7 correction of dentofacial deformities Part 2
Lecture 7 correction of dentofacial deformities Part 2
 
Lecture 8 management of patients with orofacial clefts
Lecture 8 management of patients with orofacial cleftsLecture 8 management of patients with orofacial clefts
Lecture 8 management of patients with orofacial clefts
 
Lecture 5 Diagnosis and management of salivary gland disorders Part 2
Lecture 5 Diagnosis and management of salivary gland disorders Part 2Lecture 5 Diagnosis and management of salivary gland disorders Part 2
Lecture 5 Diagnosis and management of salivary gland disorders Part 2
 
Lecture 6 correction of dentofacial deformities
Lecture 6 correction of dentofacial deformitiesLecture 6 correction of dentofacial deformities
Lecture 6 correction of dentofacial deformities
 
lecture 4 Diagnosis and management of salivary gland disorders
lecture 4 Diagnosis and management of salivary gland disorderslecture 4 Diagnosis and management of salivary gland disorders
lecture 4 Diagnosis and management of salivary gland disorders
 
Lecture 3 maxillofacial trauma part 3
Lecture 3 maxillofacial trauma part 3Lecture 3 maxillofacial trauma part 3
Lecture 3 maxillofacial trauma part 3
 
Lecture 2 maxillofacial trauma
Lecture 2 maxillofacial traumaLecture 2 maxillofacial trauma
Lecture 2 maxillofacial trauma
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

React gsg presentation with ryan jung & elias malik

  • 2. What is React? • Client-side library made and open-sourced by Facebook • Much simpler than Angular (fast learning curve) • Main goal is to be fast, scalable, and simple • React Native allows you to port over code to native iOS or Android apps
  • 3. Why Would You Use React? • Fast Learning Curve • Reusable Components which manage state • Ability to use JSX which reduces risk of XSS • Abstraction o View in MVC as opposed to client-side MVC o Use Flux/Redux as single source of truth
  • 4. React Basics – Virtual DOM / Components • Virtual DOM o React keeps an abstraction of the DOM; when changes are made, it will only re-render the elements that were changed, not the entire DOM o Makes it very fast from a performance perspective • Components o React allows you to create your own HTML elements and then define logic and state variables for these elements o 2 key methods to know: o React.Component: o Allows us to define new Components o Must have render() method o ReactDOM.render: o Lets us place Component in DOM
  • 5. React Basics - State • As noted, each Component maintains its own set of variables which programmer defines • We can set and get these state variables; when we set them, it causes the Component to re-render • We will talk about this more later, when we discuss Redux
  • 6. React Basics – Events and JSX • Components have lifecycle methods and event-based methods that will update state and re-render • For events (such as onClick or onSubmit), we access value through event.target.value -> pass this to child components if necessary, and then update state • JSX o React allows you to write HTML-like code mixed with JS to define how to render or manipulate Components
  • 7. Components can have state A complex UI usually introduces dependencies between components Parent -> Child dependencies are easy Child -> Parent and Sibling dependencies are harder The State Management Problem
  • 11. Library written by Dan Abramov (@gaeron) Built on a reducer abstraction Redux: Reducer + Flux
  • 12. Redux: Reducer + Flux Reducer Action Reducer Action State State State Action ...
  • 13. Redux: Reducer + Flux Flux Redux Update logic in stores Update logic in reducers Multiple stores Single store, multiple reducers Multiple state trees Single state atom Easy state reconstruction
  • 15. Redux reducers should be pure functions This makes testing Redux based code really easy, right? ...But how do we handle side effects? AJAX calls Web Sockets Integrating 3rd party libraries Side Effects with Redux
  • 16. New State Side Effects with Redux: Middleware Middleware 1 Middleware 2Action ... Side effect? Dispatch action? Reducer Store Store Side effect? Dispatch action?
  • 17. Many different solutions exist, variously opinionated Look at three different middlewares, and their impacts on testing: redux-thunk (@gaeron) redux-api-middleware (@agraboso) redux-saga (@yelouafi) Standard example: making an API call Side Effects with Redux: Middleware
  • 18. Side Effects with Redux: Thunks Redux-thunk allows action creators to return functions Those functions can be impure, and also dispatch other actions Generalised solution to side effects, can be used for API calls
  • 19. Side Effects with Redux: Thunks How do we test this? Action creators no longer pure functions Could mock Redux store and API call?
  • 20. Middleware that deals only with making API requests. Many existing examples. Will use “redux-api-middleware” as example. Side Effects with Redux: API middleware
  • 21. All API-related side effects isolated in (fully tested!) middleware Only need to check: Correct actions are being created Payload correctly processed Side Effects with Redux: API middleware
  • 22. Side Effects with Redux: API middleware
  • 23. Side Effects with Redux: Sagas Warning: Can be overkill for your app Significant additional abstraction Additional learning curve
  • 24. Side Effects with Redux: Sagas Generators: May be familiar from other languages (e.g. Python) Allow function execution to be paused Allow information to be passed in and out
  • 25. Side Effects with Redux: Sagas
  • 26. Side Effects with Redux: Sagas
  • 27. Side Effects with Redux: Sagas Question: So what? Added additional complexity, what have we won? Answer: Further decoupling of components Declarative actions Complex sequences of effects Easier testability of those complex sequences
  • 28. Side Effects with Redux: Sagas
  • 29. Side Effects with Redux: Sagas
  • 30. Side Effects with Redux: Sagas Utilise helper functions from redux-saga for: Delays Debouncing Throttling Dynamically creating new sagas Cancelling existing sagas
  • 31. Summary Thunks Specific Middleware Sagas General & flexible Allows building focussed API Powerful & flexible Testing requires mocking Small learning overhead Significant learning overhead Logic in action creators Easy testing Easy testing Suitable for smaller or simpler apps Suitable for most apps Suitable for large & complex apps

Notes de l'éditeur

  1. A React app consists of a component tree. Each component can have a child or a parent, and maintain own state. In apps with a relatively complex UI, there will usually be dependencies between the states of various components. Parent-child dependencies, easy. React provides solution: props More complex case: sibling dependency; state of a component depends on another not directly above it in the component hierarchy.
  2. Used to often end up in situations like this. Dependencies are managed ad-hoc, components are coupled & hold references to each other. Example: user button click should update notification bar state This is problem, what is solution?
  3. Facebook's answer to the state management problem Stores manage and reconcile state for a given _domain_ (e.g. UserStore, MapStore) Actions describe changes Dispatcher sends actions to all stores Views subscribe to store Uni-directional data flow Why is that good? Decouples components from each other. All now only depend on the store
  4. End up in situation like this Only one store here for clarity. Cleaner, and not every component needs to subscribe to the store. So that’s Flux, but this talk isn’t about Flux, it’s about Redux.
  5. Inspired by Flux, along with many other patterns; like those used in Elm and Om (ClojureScript) Built on a reducer abstraction Anyone use reduce regularly? Reducer is just a function; takes old state, and a new piece of information, returns new state Applied to collections of items
  6. Key insight of redux is to view sequences of actions as a collection in time, which can be reduced over. Same structure as reducing array of elements to single element Just that in redux, the reduction operation is never complete, because new actions can be dispatched all the time.
  7. So after implementing redux, you might end up with code that looks like this Action creator, reducer, component
  8. Middleware intercepts actions Hold references to store Can hold arbitrary code, so good place to isolate side effects Can have early returns from middleware
  9. Look at redux-api-middleware to illustrate focussed API of a middleware that is intended for specific purpose
  10. Pros: > general > lightweight > sufficient for most small React apps Cons: > Inconsistent action creator return types > Tend to put a lot of logic in action creators
  11. Explain test… This is OK, but lots of mocking is (1) annoying, (2) code smell: too much coupling / mixing of concerns Nonetheless, thunks are adequate solution for many
  12. Explain test… This is easier to test that the equivalent thunk code. Having a specific middleware focussed on isolating one class of side effect is a useful pattern in general. Also used for websockets, I’ve used it when integrating 3rd party libraries into a Redux app
  13. So what is a saga? A saga is just a generator that yields objects to the redux-saga middleware. These objects are instructions for the middleware. They come in two types: watcher sagas and worker sagas. Watchers listen for dispatched actions, while workers react to them. You can think of these sagas as daemons, or long-running processes in your app, that listen for changes. Explain example...