SlideShare a Scribd company logo
INTRODUCTION TO
Fabio Biondi / March 2018
1 / 89
JS DEVELOPER & TRAINER
Angular, React, Vue.js, Redux, RxJS, Typescript
Javascript ES6, HTML5, CSS3, SVG, Canvas
D3.js, CreateJS, TweenMax, Electron, Firebase
Facebook Groups (Developer Italiani):
Angular | React | Javascript | Opportunità/Job
Profiles:
fabiobiondi.io | LinkedIn | YouTube | CodePen | Facebook
FABIO BIONDI
2 / 89
TOPICS
COMPONENT BASED APPROACH
WHAT'S REDUX
REDUX FUNDAMENTALS
ANGULAR / REDUX examples
REACT / REDUX examples
3 / 89
In Angular, React and most of modern javascript frameworks/libs
EVERYTHING IS A COMPONENT
4 / 89
IN THE REAL WORLD :(
UI is not divided in several components
but most of the time there is only a main (big) component for each view
routes/views are often a component with a long html template
and contain a lot of business logic (JS) into it
Components are often stateful and/or there is an abuse of dependency injection
Especially in Angular
5 / 89
THE RESULT?
6 / 89
7 / 89
WHAT ARE THE PROBLEMS?
If application grows, the big picture is lost
Code is unpredictable.
Data flow is hard to follow => Mistakes and bugs are very di cult to find
App does not scale and it's not easy to mantain, to debug and to test.
If developers leave the project it can became a nightmare since projects are often
not so well-documented and nobody else really know how it works
8 / 89
A SOLUTION?
Apply properly Angular/React best practices, patterns, styleguides and
use a state management pattern, such as Redux
9 / 89
The first concept to understand is how to
organize your app in stateless components
10 / 89
COMPONENTS in ANGULAR (2+)
...
<menu [items]="users" (onItemClick)="active = $event"></menu>
<gmap [lat]="active.lat" [lng]="active.lng"></gmap>
<chart [title]="active.name" [config]="active.data"></chart>
...
What's happen here? When a menu item is selected, the google map and chart components are
populated with new data. Each component is responsable of its own behaviors and data flow should
be handled by a parent
11 / 89
SAME in REACT
...
<Menu items={users} onItemClick={active => this.setActive(active)}" />
<GMap lat={active.lat} lng={active.lng} />
<Chart title={active.name} config={active.data} />
...
12 / 89
COMPONENTS ARE THE BUILDING BLOCKS OF YOUR SPA
13 / 89
14 / 89
COMPONENT-BASED APPROACH
<navbar />
<div class="row">
<div class="col-md-4"> <!-- left column -->
<search />
<list />
<social />
</div>
<div class="col-md-8"> <!-- right column -->
<gmap />
</div>
</div>
<services />
15 / 89
TOTALLY COMPONENT-BASED
<navbar />
<row>
<card [percent]="30"> <!-- left column -->
<search />
<list />
<social />
</card>
<card [percent]="70"> <!-- right column -->
<gmap />
</card>
</row>
<services />
16 / 89
17 / 89
STATELESS APPROACH in Angular: [input] and (output)
<navbar />
<row>
<card [percent]="30">
<search (load)="hotels = $event" />
<list [items]="hotels" (itemClick)="hotel = $event" />
<social [items]="hotel.socials" />
</card>
<card [percent]="70">
<gmap [coords]="hotel.location" />
</card>
</row>
<services [items]="hotel.services" />
In React you can use the same approach 18 / 89
BY USING REDUX
<navbar />
<row>
<card [percent]="30">
<search (load)="action.load($event)" />
<list [items]="store.hotels" (itemClick)="action.select($event)"
<social [items]="store.hotel.socials" />
</card>
<card [percent]="70">
<gmap [coords]="store.hotel.location" />
</card>
</row>
<services [items]="store.hotel.services" />
19 / 89
WHY IN COMPONENTS?
Each component manages a small part of the view
Separation of concerns
Reusable
Composable
Testability
Semantic HTML: readable and simple to mantain
NOTE: components should be stateless:
just display stu and don't care about data flow
20 / 89
So, WHAT'S THE GLUE?
How components can be updated,
can communicate or stay in sync with each others ?
21 / 89
DATA ARCHITECTURES BEFORE REDUX
Frequently solutions to handle data before Redux:
1. Events => spaghetti code. Hard to manage : P
2. Dependency Injection => unpredictable :(
3. Manage state in a stateful parent component => one of the best solutions so far : )
22 / 89
23 / 89
24 / 89
25 / 89
26 / 89
Components are now framework-agnostic
27 / 89
Redux is the only one to know data and can modify it
28 / 89
HOW?
1) Avoid keeping application state in UI component itself
2) Instead we can handle it in a Redux store
State is easy to handle and it's protected by the immutability guarantees of the
Redux architecture. Dan Abramov, author of Redux
29 / 89
WHAT IS
A library that helps you manage the state
of your (large) applications
30 / 89
WHEN IS REDUX USEFUL?
SPA with complex data flow (and sophisticated UI)
Multiple views/routes that share data
Multiple components that must be in sync (with no parent relationship)
Scalability
Testability
Simplify debug
Consistently: run in di erent environments (client, server, and native)
31 / 89
32 / 89
MAIN BENEFITS
Decoupled architecture from UI
Predictable application state. One source of truth
Immutable state tree which cannot be changed directly
Components cannot mutate data. Less mistakes
Maintanibility
Organization
Scale 33 / 89
DEBUG BENEFITS
Easy to test: no mocks, spies or stubs
Redux DevTools
Track state (and di )
Track actions
Skip / Jump to actions
Time Travel Debug
Export / Import store
...
34 / 89
OTHER BENEFITS
Community
Ecosystem: a lot of Plugins & Enhancers
Persist / LocalStorage, Router, Forms, Middlewares, Log, Undo/Redo, ...
Can be shared across frameworks / libraries
React, Angular, Vue, Polymer, vanillaJS, ...
It can be used client, server (SSR) and mobile
It's (like) a pattern and used all over the world 35 / 89
But the real first thing to know about Redux is...
36 / 89
... probably you don't need Redux
37 / 89
This architecture might seem like an overkill,
but the beauty of this pattern
is how well it scales to large and complex apps.
Dan Abramov - Author of Redux
38 / 89
REDUX FUNDAMENTALS
39 / 89
THREE PRINCIPLES OF REDUX
1. Single source of truth: Store
2. State is read-only
3. Changes are made with pure functions
Source: Redux documentation
40 / 89
STORE, ACTIONS, REDUCERS: KEY-POINTS
1. The whole state of your app is stored in an object tree inside a single store.
2. The only way to change the state tree is to emit an action.
3. To specify how the actions transform the state tree, you write pure reducers.
41 / 89
REDUX FLOW
42 / 89
43 / 89
44 / 89
REDUX BUILDING BLOCKS
Store, Actions, Reducers
45 / 89
1. STORE / STATE
A single JS object that contains the current state of the application:
{
configuration: { theme: 'dark' }
auth: { token: 'abc123' }
users: {
list: [{}, {}, {}],
selected: { id: 123}
}
}
Store represents a kind of local db of your data (but it's not saved anywhere. It is in memory)
IMPORTANT: only actions can mutate the state, by using a reducer
46 / 89
STORE is a TREE of nodes
47 / 89
WHY I LOVE HAVING A SINGLE STORE? An example:
1. You (or your customer) discover a bug!
2. Store can be exported (in a JSON)
3. Store can be imported to re-create the scenario that has generated the bug
Your app must be completely stateless in order to apply this workflow
HOW? By using Redux Dev Tools. See next slides
48 / 89
2. ACTIONS
Plain JS objects that represents somethings that has happened in the application. Similar to events.
{
type: SET_CONFIG, // action type
payload: { theme: 'light' } // action payload (data)
}
{
type: USER_DELETE,
payload: 1001
}
{
type: USER_ADD,
payload: { name: 'Mario', email: ... }
}
49 / 89
You can track, jump or skip any action using REDUX Chrome DevTools
50 / 89
ACTION CREATORS
51 / 89
52 / 89
ACTION CREATORS: functions that create actions
actions/counterActions.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const increment = () => {
const action = { type: INCREMENT }; // action type
dispatch(action); // `dispatch` is provided by redux
};
export const decrement = () => {
const action = { type: DECREMENT }
dispatch(action);
};
increment and decrement methods are invoked by the UI
53 / 89
COMPONENTS invoke action creators
components/counter.component.js|ts
<!-- angular -->
<button (click)="actions.increment()"> add </button>
In Angular, actions can be injected by using a service / provider
<!-- react -->
<button onClick={ () => props.increment() }> add </button>
In React, actions are passed as props by a parent component (knows as container)
54 / 89
3. REDUCERS
A function that specify how the state changes in response to an action.
(like an event handler that determine how state must be changed)
55 / 89
A reducer never modifies the state...
// wrong!
myArray.push('anything');
myObj.property = 'anything';
56 / 89
... but it returns an (updated) copy of the state
// merge by using Lodash / Underscore => 3rd party lib
return _.merge(state, payload)
// clone current state and merge payload => ES5
return Object.assign({}, state, payload);
// same as previous => object spread operator (ES2018)
return { ...state, ...payload };
// clone array and add element => array spread operator (ES2015)
return [ ...users, payload ];
The important concept is avoid mutating the store
57 / 89
WHY WE CANNOT MUTATE THE ORIGINAL OBJECT?
1. After each action, REDUX expects a brand new object from the reducer, if there are state updates
2. Redux compares the new object with the previous one, checking the memory location
The comparison is done by using !==. A deep-compare match would be more expensive so the best
way to compare 2 object is by using the memory location
So, this comparison would not be possible if you directly modify the original state
Read a great article about this topic
58 / 89
Reducers should be a pure functions!
Same Input -> Same Output
59 / 89
What's an inpure function?
Any function that doesn’t alter data and doesn’t depend on external state (like DB, DOM, or global variables)
function increment(obj) {
obj.count++; // NO mutate arguments
}
function increment(user) {
service.doSomething(user); // NO side effects
}
function increment(input) {
obj.count = Math.random(); // NO random, new Date(), ...
}
60 / 89
Pure functions
Instead of the following:
function increment(state) {
state.count++; // NO! mutate the state
}
A pure function should return a new copy of the object:
function increment(state) {
return {
count: state.count + 1 // OK! return a new state
};
}
61 / 89
REDUCERS
62 / 89
REDUCERS mutate state
reducers/counter.reducer.js
const INITIAL_STATE = { count: 0 };
function CounterReducer(state = INITIAL_STATE, action: any) {
switch (action.type) {
case INCREMENT:
return { count: state.count + 1 };
case DECREMENT:
return { count: state.count - 1 };
default:
return state; // always return state as default
}
}
Reducers are automatically processed each time an action is invoked 63 / 89
64 / 89
REDUX EXAMPLES
with Angular & React
65 / 89
angular-redux/store
npm install redux @angular-redux/store
66 / 89
LIVE EXAMPLE - REDUX COUNTER
67 / 89
/app/app.component.ts
1 i
EDITOR PREVIEW
EDIT ON STACKBLITZ
68 / 89
CRUD REDUX APP
in 5 steps
69 / 89
1. ROOT REDUCER: store structure
// store/index.ts
import { combineReducers } from 'redux';
import { User, Configuration, Auth } from '../model';
import { UsersReducer, ConfigReducer, AuthReducer } from './store';
export class IAppState {
users: User[]; // <===
config: Configuration;
auth: Auth;
};
export const rootReducer = combineReducers<IAppState>({
users: UsersReducer, // <===
config: ConfigReducer,
auth: AuthReducer
});
70 / 89
2. CONFIGURE REDUX
// app.module.ts
@NgModule({
imports: [ NgReduxModule ], // <== redux module
declarations: [ AppComponent ],
providers: [ UsersActions, ConfigActions ], // <== actions
bootstrap: [ AppComponent ]
})
export class AppModule {
constructor( private ngRedux: NgRedux<IAppState> ) {
this.ngRedux.configureStore( rootReducer, {}); // <== init redux
}
}
71 / 89
3. REDUCER
// store/users.reducer.ts
const INIT_STATE: User[] = [];
export function UsersReducer(state: User[] = INIT_STATE, action: any) {
switch (action.type) {
case UsersActions.USERS_ADD: // Add user to state
return [...state, action.payload];
case UsersActions.USERS_DELETE: // Remove user from state
return state.filter(user => user.id !== action.payload.id);
default:
return state;
}
}
72 / 89
4. ACTION CREATOR (with async operations)
// actions/users.actions.ts
@Injectable()
export class UsersActions {
static USERS_ADD = 'USERS_ADD';
static USERS_DELETE = 'USERS_DELETE';
/* ... missing ... */ }
add(user: User): void {
this.http.post<User>('api/users/', user)
.subscribe((newUser: User) => {
this.ngRedux.dispatch({ // dispatch action
type: UsersActions.USERS_ADD,
payload: newUser // The new user
});
});
}
} 73 / 89
5A. VIEW: get State
// views/dashboard.component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from '../model/user';
@Component({
selector: 'dashboard',
template: '<list [data]="myUsers"></list>'
})
export class DashboardComponent {
@select('users') public users$: Observable<User[]>; // select state
myUsers: User[];
constructor() {
this.users$.subscribe(res => this.myUsers = res);
}
} 74 / 89
5B. VIEW: get State and async pipe
// views/dashboard.component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from '../model/user';
@Component({
selector: 'dashboard',
template: '<list [data]="myUsers | async"></list>'
})
export class DashboardComponent {
@select('users') public users$: Observable<User[]>; // select
}
75 / 89
5C. VIEW: get state and invoke actions
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from '../model/user';
import { UsersActions } from '../actions/users.actions';
@Component({
selector: 'dashboard',
template: `<list [data]="users$ | async"
(delete)="actions.deleteUser($event)"></list>`
})
export class DashboardComponent {
@select('users') public users$: Observable<User[]>; // select
constructor(public actions: UsersActions) {
actions.getUsers();
}
}
76 / 89
Do NOT you like to angular-redux/store?
Try ngrx. It's awesome!
ngrx is not a Redux binding (as Angular Redux/Store), it has been written from scratch and it widely
use RxJS. It also includes middlewares, memoization, lazy-store/e ects and a lot of other cool stu
out of the box.
Anyway Angular Redux/Store is easier to learn.
77 / 89
MIDDLEWARES
NGRX e ects, Angular Redux Epics, Redux Thunk, Redux Observable, ...
78 / 89
79 / 89
Middleware in Angular by using React Thunk (used in Angular, React, ...)
export const USER_PENDING = 'USER_PENDING';
export const USER_ERROR = 'USER_ERROR';
export const USER_ADD = 'USER_ADD';
export const pendingAction = params => {
return { type: USER_PENDING, pending: true, error: false }
};
export const errorAction = error => {
return { type: USER_ERROR, pending: false, error }
};
export const addAction = user => {
return { type: USER_ADD, user, pending: false, error: false }
};
export function addUser(user) {
return function (dispatch) {
dispatch(pendingAction(user)); // Pending Action
return axios.post('/api/user', { ...user })
.then(res => dispatch(addAction(res.data))) // Success Action
.catch(error => dispatch(errorAction(error))) // Error Action
}
}
80 / 89
Middleware in Angular by using NGRX E ects (and RxJS 5.5+)
@Injectable()
export class UsersEffects {
// ...
@Effect() addUser$ = this.actions$.ofType<AddUser>(UsersActions.ADD)
.mergeMap((action: AddUser) =>
this.http.post('/api/users', user)
.pipe(
map(data => ({ type: UsersActions.ADD_SUCCESS, payload: data })),
catchError(() => of({ type: UsersActions.ADD_FAILED }))
)
);
// ...
constructor(
private http: HttpClient,
private actions$: Actions
) {}
}
81 / 89
REACT & REDUX
82 / 89
Main Application Component
// index.js
import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from ''./reducers';
import App from './App';
const store = createStore(rootReducer);
render(<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
WHAT WE DID: initialize Redux Store
83 / 89
App: application root component
Connect Redux to components
// app.jsx
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<NavBar />
<Route exact path="/" component={HomeContainer} />
<Route path="/dashboard" component={DashboardContainer} />
<Route path="/another" component={AnotherContainer} />
</div>
</BrowserRouter>
);
}
}
84 / 89
Dashboard: Container
Connect Redux to components
// views/DashboardContainer.jsx
import * as React from 'react';
import { connect } from 'react-redux';
import { addUser, deleteUser } from "../../actions/usersActions";
import { DashboardView } from './view/dashboard';
const DashboardContainer = connect(
state => ({ users: state.users }),
{ addUser, deleteUser }
)(DashboardView);
export default DashboardContainer;
WHAT WE DID: we sent state and actions to the DashboardView component as props 85 / 89
DashboardView: Presentational component
Get state from redux (by props) and invoke actions
// views/DashboardView.jsx
export const DashboardView = props => (
<div>
<h1>{props.users.length} members</h1>
<AddForm submit={user => props.addUser(user)}/>
<Users {{...props}} onDelete={id => props.deleteUser(id)} />
</div>
);
Presentational components should know nothing about Redux,
so you can reuse them without it as well.
86 / 89
And now? There's still a lot of stu to learn
Read the Redux Documentation
Watch "Getting Started with Redux" videos by Dan Abramov
Check the Redux binding for your favorite library
Join my training courses: fabiobiondi.io ;)
87 / 89
Facebook Groups:
ANGULAR - Developer Italiani
REACT Developer Italiani
JAVASCRIPT Developer Italiani
OPPORTUNITÀ Developer Italiani
88 / 89
fabiobiondi.io
FOLLOW ME ON:
Facebook | YouTube | CodePen| LinkedIn
89 / 89
Ad

More Related Content

What's hot (20)

Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
Introduction to React Hooks
Introduction to React HooksIntroduction to React Hooks
Introduction to React Hooks
Felicia O'Garro
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
Andrii Lundiak
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
Ivan Paulovich
 
Context API in React
Context API in ReactContext API in React
Context API in React
Lucas Lira Gomes
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
Clean code: SOLID
Clean code: SOLIDClean code: SOLID
Clean code: SOLID
Indeema Software Inc.
 
The virtual DOM and how react uses it internally
The virtual DOM and how react uses it internallyThe virtual DOM and how react uses it internally
The virtual DOM and how react uses it internally
Clóvis Neto
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
Nitin Tyagi
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
manojbkalla
 
Introduzione ad angular 7/8
Introduzione ad angular 7/8Introduzione ad angular 7/8
Introduzione ad angular 7/8
Valerio Radice
 
React js
React jsReact js
React js
Nikhil Karkra
 
Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...
Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...
Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...
Edureka!
 
React hooks
React hooksReact hooks
React hooks
Assaf Gannon
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
Tomáš Drenčák
 
Git branching strategies
Git branching strategiesGit branching strategies
Git branching strategies
jstack
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
Introduction to React Hooks
Introduction to React HooksIntroduction to React Hooks
Introduction to React Hooks
Felicia O'Garro
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
Andrii Lundiak
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
Ivan Paulovich
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
The virtual DOM and how react uses it internally
The virtual DOM and how react uses it internallyThe virtual DOM and how react uses it internally
The virtual DOM and how react uses it internally
Clóvis Neto
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
Nitin Tyagi
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
manojbkalla
 
Introduzione ad angular 7/8
Introduzione ad angular 7/8Introduzione ad angular 7/8
Introduzione ad angular 7/8
Valerio Radice
 
Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...
Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...
Angular 4 Data Binding | Two Way Data Binding in Angular 4 | Angular 4 Tutori...
Edureka!
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
Tomáš Drenčák
 
Git branching strategies
Git branching strategiesGit branching strategies
Git branching strategies
jstack
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 

Similar to Introduction to Redux (for Angular and React devs) (20)

Materi Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdfMateri Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdf
exiabreak
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
Chiew Carol
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
Amin Ashtiani
 
Redux
ReduxRedux
Redux
Maulik Shah
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
Jean Carlo Emer
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
David Barreto
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
David Barreto
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
Gabor Varadi
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 
Session 03_04-Working with React Native.pptx
Session 03_04-Working with React Native.pptxSession 03_04-Working with React Native.pptx
Session 03_04-Working with React Native.pptx
VHiu94
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
valuebound
 
How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react
MoonTechnolabsPvtLtd
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...
Katy Slemon
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
Knoldus Inc.
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
Vibrant Technologies & Computers
 
ReactJS.pptx
ReactJS.pptxReactJS.pptx
ReactJS.pptx
SamyakShetty2
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
BOSC Tech Labs
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware Architecture
Mateusz Bosek
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
Paul Gallagher
 
Materi Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdfMateri Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdf
exiabreak
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
Chiew Carol
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
Amin Ashtiani
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
Jean Carlo Emer
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
David Barreto
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
David Barreto
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
Gabor Varadi
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 
Session 03_04-Working with React Native.pptx
Session 03_04-Working with React Native.pptxSession 03_04-Working with React Native.pptx
Session 03_04-Working with React Native.pptx
VHiu94
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
valuebound
 
How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react
MoonTechnolabsPvtLtd
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...
Katy Slemon
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
Knoldus Inc.
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
BOSC Tech Labs
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware Architecture
Mateusz Bosek
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
Paul Gallagher
 
Ad

More from Fabio Biondi (16)

React - Component Based Approach
React - Component Based ApproachReact - Component Based Approach
React - Component Based Approach
Fabio Biondi
 
Introduction to E2E in Cypress
Introduction to E2E in CypressIntroduction to E2E in Cypress
Introduction to E2E in Cypress
Fabio Biondi
 
Create your React 18 / TS bundle using esbuild
Create your React 18 / TS bundle using esbuildCreate your React 18 / TS bundle using esbuild
Create your React 18 / TS bundle using esbuild
Fabio Biondi
 
Create Web Components using Google Lit
Create Web Components using Google LitCreate Web Components using Google Lit
Create Web Components using Google Lit
Fabio Biondi
 
Redux Toolkit & RTK Query in TypeScript: tips&tricks
Redux Toolkit & RTK Query in TypeScript: tips&tricksRedux Toolkit & RTK Query in TypeScript: tips&tricks
Redux Toolkit & RTK Query in TypeScript: tips&tricks
Fabio Biondi
 
React Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive servicesReact Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive services
Fabio Biondi
 
RXJS Best (& Bad) Practices for Angular Developers
RXJS Best (& Bad) Practices for Angular DevelopersRXJS Best (& Bad) Practices for Angular Developers
RXJS Best (& Bad) Practices for Angular Developers
Fabio Biondi
 
Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"
Fabio Biondi
 
Data architectures in Angular & NGRX Introduction
Data architectures in Angular & NGRX IntroductionData architectures in Angular & NGRX Introduction
Data architectures in Angular & NGRX Introduction
Fabio Biondi
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
Fabio Biondi
 
Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6
Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6
Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6
Fabio Biondi
 
Angular Best Practices @ Firenze 19 feb 2018
Angular Best Practices @ Firenze 19 feb 2018Angular Best Practices @ Firenze 19 feb 2018
Angular Best Practices @ Firenze 19 feb 2018
Fabio Biondi
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
Fabio Biondi
 
Intro evento: evolvere un applicazione Angular con Rxjs e Redux
Intro evento: evolvere un applicazione Angular con Rxjs e ReduxIntro evento: evolvere un applicazione Angular con Rxjs e Redux
Intro evento: evolvere un applicazione Angular con Rxjs e Redux
Fabio Biondi
 
Single Page Applications in Angular (italiano)
Single Page Applications in Angular (italiano)Single Page Applications in Angular (italiano)
Single Page Applications in Angular (italiano)
Fabio Biondi
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core Concepts
Fabio Biondi
 
React - Component Based Approach
React - Component Based ApproachReact - Component Based Approach
React - Component Based Approach
Fabio Biondi
 
Introduction to E2E in Cypress
Introduction to E2E in CypressIntroduction to E2E in Cypress
Introduction to E2E in Cypress
Fabio Biondi
 
Create your React 18 / TS bundle using esbuild
Create your React 18 / TS bundle using esbuildCreate your React 18 / TS bundle using esbuild
Create your React 18 / TS bundle using esbuild
Fabio Biondi
 
Create Web Components using Google Lit
Create Web Components using Google LitCreate Web Components using Google Lit
Create Web Components using Google Lit
Fabio Biondi
 
Redux Toolkit & RTK Query in TypeScript: tips&tricks
Redux Toolkit & RTK Query in TypeScript: tips&tricksRedux Toolkit & RTK Query in TypeScript: tips&tricks
Redux Toolkit & RTK Query in TypeScript: tips&tricks
Fabio Biondi
 
React Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive servicesReact Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive services
Fabio Biondi
 
RXJS Best (& Bad) Practices for Angular Developers
RXJS Best (& Bad) Practices for Angular DevelopersRXJS Best (& Bad) Practices for Angular Developers
RXJS Best (& Bad) Practices for Angular Developers
Fabio Biondi
 
Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"
Fabio Biondi
 
Data architectures in Angular & NGRX Introduction
Data architectures in Angular & NGRX IntroductionData architectures in Angular & NGRX Introduction
Data architectures in Angular & NGRX Introduction
Fabio Biondi
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
Fabio Biondi
 
Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6
Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6
Angular Day 2018 (italy) - Keynote - The Amazing World of Angular 6
Fabio Biondi
 
Angular Best Practices @ Firenze 19 feb 2018
Angular Best Practices @ Firenze 19 feb 2018Angular Best Practices @ Firenze 19 feb 2018
Angular Best Practices @ Firenze 19 feb 2018
Fabio Biondi
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
Fabio Biondi
 
Intro evento: evolvere un applicazione Angular con Rxjs e Redux
Intro evento: evolvere un applicazione Angular con Rxjs e ReduxIntro evento: evolvere un applicazione Angular con Rxjs e Redux
Intro evento: evolvere un applicazione Angular con Rxjs e Redux
Fabio Biondi
 
Single Page Applications in Angular (italiano)
Single Page Applications in Angular (italiano)Single Page Applications in Angular (italiano)
Single Page Applications in Angular (italiano)
Fabio Biondi
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core Concepts
Fabio Biondi
 
Ad

Recently uploaded (20)

Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
File Viewer Plus 7.5.5.49 Crack Full Version
File Viewer Plus 7.5.5.49 Crack Full VersionFile Viewer Plus 7.5.5.49 Crack Full Version
File Viewer Plus 7.5.5.49 Crack Full Version
raheemk1122g
 
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
jamesmartin143256
 
User interface and User experience Modernization.pptx
User interface and User experience  Modernization.pptxUser interface and User experience  Modernization.pptx
User interface and User experience Modernization.pptx
MustafaAlshekly1
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Hyper Casual Game Developers Company
Hyper  Casual  Game  Developers  CompanyHyper  Casual  Game  Developers  Company
Hyper Casual Game Developers Company
Nova Carter
 
iTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation KeyiTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation Key
raheemk1122g
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
UI/UX Design & Development and Servicess
UI/UX Design & Development and ServicessUI/UX Design & Development and Servicess
UI/UX Design & Development and Servicess
marketing810348
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
File Viewer Plus 7.5.5.49 Crack Full Version
File Viewer Plus 7.5.5.49 Crack Full VersionFile Viewer Plus 7.5.5.49 Crack Full Version
File Viewer Plus 7.5.5.49 Crack Full Version
raheemk1122g
 
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
jamesmartin143256
 
User interface and User experience Modernization.pptx
User interface and User experience  Modernization.pptxUser interface and User experience  Modernization.pptx
User interface and User experience Modernization.pptx
MustafaAlshekly1
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Hyper Casual Game Developers Company
Hyper  Casual  Game  Developers  CompanyHyper  Casual  Game  Developers  Company
Hyper Casual Game Developers Company
Nova Carter
 
iTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation KeyiTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation Key
raheemk1122g
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
UI/UX Design & Development and Servicess
UI/UX Design & Development and ServicessUI/UX Design & Development and Servicess
UI/UX Design & Development and Servicess
marketing810348
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo
 

Introduction to Redux (for Angular and React devs)

  • 1. INTRODUCTION TO Fabio Biondi / March 2018 1 / 89
  • 2. JS DEVELOPER & TRAINER Angular, React, Vue.js, Redux, RxJS, Typescript Javascript ES6, HTML5, CSS3, SVG, Canvas D3.js, CreateJS, TweenMax, Electron, Firebase Facebook Groups (Developer Italiani): Angular | React | Javascript | Opportunità/Job Profiles: fabiobiondi.io | LinkedIn | YouTube | CodePen | Facebook FABIO BIONDI 2 / 89
  • 3. TOPICS COMPONENT BASED APPROACH WHAT'S REDUX REDUX FUNDAMENTALS ANGULAR / REDUX examples REACT / REDUX examples 3 / 89
  • 4. In Angular, React and most of modern javascript frameworks/libs EVERYTHING IS A COMPONENT 4 / 89
  • 5. IN THE REAL WORLD :( UI is not divided in several components but most of the time there is only a main (big) component for each view routes/views are often a component with a long html template and contain a lot of business logic (JS) into it Components are often stateful and/or there is an abuse of dependency injection Especially in Angular 5 / 89
  • 8. WHAT ARE THE PROBLEMS? If application grows, the big picture is lost Code is unpredictable. Data flow is hard to follow => Mistakes and bugs are very di cult to find App does not scale and it's not easy to mantain, to debug and to test. If developers leave the project it can became a nightmare since projects are often not so well-documented and nobody else really know how it works 8 / 89
  • 9. A SOLUTION? Apply properly Angular/React best practices, patterns, styleguides and use a state management pattern, such as Redux 9 / 89
  • 10. The first concept to understand is how to organize your app in stateless components 10 / 89
  • 11. COMPONENTS in ANGULAR (2+) ... <menu [items]="users" (onItemClick)="active = $event"></menu> <gmap [lat]="active.lat" [lng]="active.lng"></gmap> <chart [title]="active.name" [config]="active.data"></chart> ... What's happen here? When a menu item is selected, the google map and chart components are populated with new data. Each component is responsable of its own behaviors and data flow should be handled by a parent 11 / 89
  • 12. SAME in REACT ... <Menu items={users} onItemClick={active => this.setActive(active)}" /> <GMap lat={active.lat} lng={active.lng} /> <Chart title={active.name} config={active.data} /> ... 12 / 89
  • 13. COMPONENTS ARE THE BUILDING BLOCKS OF YOUR SPA 13 / 89
  • 15. COMPONENT-BASED APPROACH <navbar /> <div class="row"> <div class="col-md-4"> <!-- left column --> <search /> <list /> <social /> </div> <div class="col-md-8"> <!-- right column --> <gmap /> </div> </div> <services /> 15 / 89
  • 16. TOTALLY COMPONENT-BASED <navbar /> <row> <card [percent]="30"> <!-- left column --> <search /> <list /> <social /> </card> <card [percent]="70"> <!-- right column --> <gmap /> </card> </row> <services /> 16 / 89
  • 18. STATELESS APPROACH in Angular: [input] and (output) <navbar /> <row> <card [percent]="30"> <search (load)="hotels = $event" /> <list [items]="hotels" (itemClick)="hotel = $event" /> <social [items]="hotel.socials" /> </card> <card [percent]="70"> <gmap [coords]="hotel.location" /> </card> </row> <services [items]="hotel.services" /> In React you can use the same approach 18 / 89
  • 19. BY USING REDUX <navbar /> <row> <card [percent]="30"> <search (load)="action.load($event)" /> <list [items]="store.hotels" (itemClick)="action.select($event)" <social [items]="store.hotel.socials" /> </card> <card [percent]="70"> <gmap [coords]="store.hotel.location" /> </card> </row> <services [items]="store.hotel.services" /> 19 / 89
  • 20. WHY IN COMPONENTS? Each component manages a small part of the view Separation of concerns Reusable Composable Testability Semantic HTML: readable and simple to mantain NOTE: components should be stateless: just display stu and don't care about data flow 20 / 89
  • 21. So, WHAT'S THE GLUE? How components can be updated, can communicate or stay in sync with each others ? 21 / 89
  • 22. DATA ARCHITECTURES BEFORE REDUX Frequently solutions to handle data before Redux: 1. Events => spaghetti code. Hard to manage : P 2. Dependency Injection => unpredictable :( 3. Manage state in a stateful parent component => one of the best solutions so far : ) 22 / 89
  • 27. Components are now framework-agnostic 27 / 89
  • 28. Redux is the only one to know data and can modify it 28 / 89
  • 29. HOW? 1) Avoid keeping application state in UI component itself 2) Instead we can handle it in a Redux store State is easy to handle and it's protected by the immutability guarantees of the Redux architecture. Dan Abramov, author of Redux 29 / 89
  • 30. WHAT IS A library that helps you manage the state of your (large) applications 30 / 89
  • 31. WHEN IS REDUX USEFUL? SPA with complex data flow (and sophisticated UI) Multiple views/routes that share data Multiple components that must be in sync (with no parent relationship) Scalability Testability Simplify debug Consistently: run in di erent environments (client, server, and native) 31 / 89
  • 33. MAIN BENEFITS Decoupled architecture from UI Predictable application state. One source of truth Immutable state tree which cannot be changed directly Components cannot mutate data. Less mistakes Maintanibility Organization Scale 33 / 89
  • 34. DEBUG BENEFITS Easy to test: no mocks, spies or stubs Redux DevTools Track state (and di ) Track actions Skip / Jump to actions Time Travel Debug Export / Import store ... 34 / 89
  • 35. OTHER BENEFITS Community Ecosystem: a lot of Plugins & Enhancers Persist / LocalStorage, Router, Forms, Middlewares, Log, Undo/Redo, ... Can be shared across frameworks / libraries React, Angular, Vue, Polymer, vanillaJS, ... It can be used client, server (SSR) and mobile It's (like) a pattern and used all over the world 35 / 89
  • 36. But the real first thing to know about Redux is... 36 / 89
  • 37. ... probably you don't need Redux 37 / 89
  • 38. This architecture might seem like an overkill, but the beauty of this pattern is how well it scales to large and complex apps. Dan Abramov - Author of Redux 38 / 89
  • 40. THREE PRINCIPLES OF REDUX 1. Single source of truth: Store 2. State is read-only 3. Changes are made with pure functions Source: Redux documentation 40 / 89
  • 41. STORE, ACTIONS, REDUCERS: KEY-POINTS 1. The whole state of your app is stored in an object tree inside a single store. 2. The only way to change the state tree is to emit an action. 3. To specify how the actions transform the state tree, you write pure reducers. 41 / 89
  • 45. REDUX BUILDING BLOCKS Store, Actions, Reducers 45 / 89
  • 46. 1. STORE / STATE A single JS object that contains the current state of the application: { configuration: { theme: 'dark' } auth: { token: 'abc123' } users: { list: [{}, {}, {}], selected: { id: 123} } } Store represents a kind of local db of your data (but it's not saved anywhere. It is in memory) IMPORTANT: only actions can mutate the state, by using a reducer 46 / 89
  • 47. STORE is a TREE of nodes 47 / 89
  • 48. WHY I LOVE HAVING A SINGLE STORE? An example: 1. You (or your customer) discover a bug! 2. Store can be exported (in a JSON) 3. Store can be imported to re-create the scenario that has generated the bug Your app must be completely stateless in order to apply this workflow HOW? By using Redux Dev Tools. See next slides 48 / 89
  • 49. 2. ACTIONS Plain JS objects that represents somethings that has happened in the application. Similar to events. { type: SET_CONFIG, // action type payload: { theme: 'light' } // action payload (data) } { type: USER_DELETE, payload: 1001 } { type: USER_ADD, payload: { name: 'Mario', email: ... } } 49 / 89
  • 50. You can track, jump or skip any action using REDUX Chrome DevTools 50 / 89
  • 53. ACTION CREATORS: functions that create actions actions/counterActions.js export const INCREMENT = 'INCREMENT'; export const DECREMENT = 'DECREMENT'; export const increment = () => { const action = { type: INCREMENT }; // action type dispatch(action); // `dispatch` is provided by redux }; export const decrement = () => { const action = { type: DECREMENT } dispatch(action); }; increment and decrement methods are invoked by the UI 53 / 89
  • 54. COMPONENTS invoke action creators components/counter.component.js|ts <!-- angular --> <button (click)="actions.increment()"> add </button> In Angular, actions can be injected by using a service / provider <!-- react --> <button onClick={ () => props.increment() }> add </button> In React, actions are passed as props by a parent component (knows as container) 54 / 89
  • 55. 3. REDUCERS A function that specify how the state changes in response to an action. (like an event handler that determine how state must be changed) 55 / 89
  • 56. A reducer never modifies the state... // wrong! myArray.push('anything'); myObj.property = 'anything'; 56 / 89
  • 57. ... but it returns an (updated) copy of the state // merge by using Lodash / Underscore => 3rd party lib return _.merge(state, payload) // clone current state and merge payload => ES5 return Object.assign({}, state, payload); // same as previous => object spread operator (ES2018) return { ...state, ...payload }; // clone array and add element => array spread operator (ES2015) return [ ...users, payload ]; The important concept is avoid mutating the store 57 / 89
  • 58. WHY WE CANNOT MUTATE THE ORIGINAL OBJECT? 1. After each action, REDUX expects a brand new object from the reducer, if there are state updates 2. Redux compares the new object with the previous one, checking the memory location The comparison is done by using !==. A deep-compare match would be more expensive so the best way to compare 2 object is by using the memory location So, this comparison would not be possible if you directly modify the original state Read a great article about this topic 58 / 89
  • 59. Reducers should be a pure functions! Same Input -> Same Output 59 / 89
  • 60. What's an inpure function? Any function that doesn’t alter data and doesn’t depend on external state (like DB, DOM, or global variables) function increment(obj) { obj.count++; // NO mutate arguments } function increment(user) { service.doSomething(user); // NO side effects } function increment(input) { obj.count = Math.random(); // NO random, new Date(), ... } 60 / 89
  • 61. Pure functions Instead of the following: function increment(state) { state.count++; // NO! mutate the state } A pure function should return a new copy of the object: function increment(state) { return { count: state.count + 1 // OK! return a new state }; } 61 / 89
  • 63. REDUCERS mutate state reducers/counter.reducer.js const INITIAL_STATE = { count: 0 }; function CounterReducer(state = INITIAL_STATE, action: any) { switch (action.type) { case INCREMENT: return { count: state.count + 1 }; case DECREMENT: return { count: state.count - 1 }; default: return state; // always return state as default } } Reducers are automatically processed each time an action is invoked 63 / 89
  • 65. REDUX EXAMPLES with Angular & React 65 / 89
  • 66. angular-redux/store npm install redux @angular-redux/store 66 / 89
  • 67. LIVE EXAMPLE - REDUX COUNTER 67 / 89
  • 69. CRUD REDUX APP in 5 steps 69 / 89
  • 70. 1. ROOT REDUCER: store structure // store/index.ts import { combineReducers } from 'redux'; import { User, Configuration, Auth } from '../model'; import { UsersReducer, ConfigReducer, AuthReducer } from './store'; export class IAppState { users: User[]; // <=== config: Configuration; auth: Auth; }; export const rootReducer = combineReducers<IAppState>({ users: UsersReducer, // <=== config: ConfigReducer, auth: AuthReducer }); 70 / 89
  • 71. 2. CONFIGURE REDUX // app.module.ts @NgModule({ imports: [ NgReduxModule ], // <== redux module declarations: [ AppComponent ], providers: [ UsersActions, ConfigActions ], // <== actions bootstrap: [ AppComponent ] }) export class AppModule { constructor( private ngRedux: NgRedux<IAppState> ) { this.ngRedux.configureStore( rootReducer, {}); // <== init redux } } 71 / 89
  • 72. 3. REDUCER // store/users.reducer.ts const INIT_STATE: User[] = []; export function UsersReducer(state: User[] = INIT_STATE, action: any) { switch (action.type) { case UsersActions.USERS_ADD: // Add user to state return [...state, action.payload]; case UsersActions.USERS_DELETE: // Remove user from state return state.filter(user => user.id !== action.payload.id); default: return state; } } 72 / 89
  • 73. 4. ACTION CREATOR (with async operations) // actions/users.actions.ts @Injectable() export class UsersActions { static USERS_ADD = 'USERS_ADD'; static USERS_DELETE = 'USERS_DELETE'; /* ... missing ... */ } add(user: User): void { this.http.post<User>('api/users/', user) .subscribe((newUser: User) => { this.ngRedux.dispatch({ // dispatch action type: UsersActions.USERS_ADD, payload: newUser // The new user }); }); } } 73 / 89
  • 74. 5A. VIEW: get State // views/dashboard.component.ts import { Component } from '@angular/core'; import { Observable } from 'rxjs'; import { User } from '../model/user'; @Component({ selector: 'dashboard', template: '<list [data]="myUsers"></list>' }) export class DashboardComponent { @select('users') public users$: Observable<User[]>; // select state myUsers: User[]; constructor() { this.users$.subscribe(res => this.myUsers = res); } } 74 / 89
  • 75. 5B. VIEW: get State and async pipe // views/dashboard.component.ts import { Component } from '@angular/core'; import { Observable } from 'rxjs'; import { User } from '../model/user'; @Component({ selector: 'dashboard', template: '<list [data]="myUsers | async"></list>' }) export class DashboardComponent { @select('users') public users$: Observable<User[]>; // select } 75 / 89
  • 76. 5C. VIEW: get state and invoke actions import { Component } from '@angular/core'; import { Observable } from 'rxjs'; import { User } from '../model/user'; import { UsersActions } from '../actions/users.actions'; @Component({ selector: 'dashboard', template: `<list [data]="users$ | async" (delete)="actions.deleteUser($event)"></list>` }) export class DashboardComponent { @select('users') public users$: Observable<User[]>; // select constructor(public actions: UsersActions) { actions.getUsers(); } } 76 / 89
  • 77. Do NOT you like to angular-redux/store? Try ngrx. It's awesome! ngrx is not a Redux binding (as Angular Redux/Store), it has been written from scratch and it widely use RxJS. It also includes middlewares, memoization, lazy-store/e ects and a lot of other cool stu out of the box. Anyway Angular Redux/Store is easier to learn. 77 / 89
  • 78. MIDDLEWARES NGRX e ects, Angular Redux Epics, Redux Thunk, Redux Observable, ... 78 / 89
  • 80. Middleware in Angular by using React Thunk (used in Angular, React, ...) export const USER_PENDING = 'USER_PENDING'; export const USER_ERROR = 'USER_ERROR'; export const USER_ADD = 'USER_ADD'; export const pendingAction = params => { return { type: USER_PENDING, pending: true, error: false } }; export const errorAction = error => { return { type: USER_ERROR, pending: false, error } }; export const addAction = user => { return { type: USER_ADD, user, pending: false, error: false } }; export function addUser(user) { return function (dispatch) { dispatch(pendingAction(user)); // Pending Action return axios.post('/api/user', { ...user }) .then(res => dispatch(addAction(res.data))) // Success Action .catch(error => dispatch(errorAction(error))) // Error Action } } 80 / 89
  • 81. Middleware in Angular by using NGRX E ects (and RxJS 5.5+) @Injectable() export class UsersEffects { // ... @Effect() addUser$ = this.actions$.ofType<AddUser>(UsersActions.ADD) .mergeMap((action: AddUser) => this.http.post('/api/users', user) .pipe( map(data => ({ type: UsersActions.ADD_SUCCESS, payload: data })), catchError(() => of({ type: UsersActions.ADD_FAILED })) ) ); // ... constructor( private http: HttpClient, private actions$: Actions ) {} } 81 / 89
  • 83. Main Application Component // index.js import React from 'react'; import { render } from 'react-dom'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from ''./reducers'; import App from './App'; const store = createStore(rootReducer); render(<Provider store={store}> <App /> </Provider>, document.getElementById('root')); WHAT WE DID: initialize Redux Store 83 / 89
  • 84. App: application root component Connect Redux to components // app.jsx class App extends Component { render() { return ( <BrowserRouter> <div> <NavBar /> <Route exact path="/" component={HomeContainer} /> <Route path="/dashboard" component={DashboardContainer} /> <Route path="/another" component={AnotherContainer} /> </div> </BrowserRouter> ); } } 84 / 89
  • 85. Dashboard: Container Connect Redux to components // views/DashboardContainer.jsx import * as React from 'react'; import { connect } from 'react-redux'; import { addUser, deleteUser } from "../../actions/usersActions"; import { DashboardView } from './view/dashboard'; const DashboardContainer = connect( state => ({ users: state.users }), { addUser, deleteUser } )(DashboardView); export default DashboardContainer; WHAT WE DID: we sent state and actions to the DashboardView component as props 85 / 89
  • 86. DashboardView: Presentational component Get state from redux (by props) and invoke actions // views/DashboardView.jsx export const DashboardView = props => ( <div> <h1>{props.users.length} members</h1> <AddForm submit={user => props.addUser(user)}/> <Users {{...props}} onDelete={id => props.deleteUser(id)} /> </div> ); Presentational components should know nothing about Redux, so you can reuse them without it as well. 86 / 89
  • 87. And now? There's still a lot of stu to learn Read the Redux Documentation Watch "Getting Started with Redux" videos by Dan Abramov Check the Redux binding for your favorite library Join my training courses: fabiobiondi.io ;) 87 / 89
  • 88. Facebook Groups: ANGULAR - Developer Italiani REACT Developer Italiani JAVASCRIPT Developer Italiani OPPORTUNITÀ Developer Italiani 88 / 89
  • 89. fabiobiondi.io FOLLOW ME ON: Facebook | YouTube | CodePen| LinkedIn 89 / 89
  翻译: