SlideShare a Scribd company logo
1 of 47
React + Redux
React + Redux @nikgraf
Nik Graf
@nikgraf
nik@nikgraf.com
Creator of Belle (UI Components)
Working with StarterSquad
Travelled around the World
React + Redux @nikgraf
ECMAScript2015
const sum = (first, second) => {
return first + second;
}
React + Redux @nikgraf
Created by Sebastian McKenzie
- ECMAScript 2015 Support, JSX Support
- Widely adopted
Let’s get started
Source: https://www.flickr.com/photos/mike52ad/
React + Redux @nikgraf
React
React is a JavaScript Library for building user
interfaces.
• Focus on the UI, not a Framework
• One-way reactive data flow (no two-way data binding)
• Virtual DOM
React + Redux @nikgraf
Virtual DOM
Keep track of state in DOM is hard.
The DOM API is slow.
(Try to re-render the whole DOM on every change)
React + Redux @nikgraf
Virtual DOM
Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
React + Redux @nikgraf
Virtual DOM
Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
React + Redux @nikgraf
Virtual DOM Benefits
Batched DOM read/write operations.
Efficient update of sub-tree only.
React + Redux @nikgraf
Our first Experiment Part I
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="bundle.js"></script>
</head>
<body>
<div id="example"></div>
</body>
</html>
index.html
React + Redux @nikgraf
Our first Experiment Part II
import React from 'react';
import ReactDOM from 'react-dom';
const exampleElement = document.getElementById('example');
ReactDOM.render(<h1>Hello, world!</h1>, exampleElement);
main.js -> bundle.js
React + Redux @nikgraf
JSX
JSX is a JavaScript syntax extension
that looks similar to XML.
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = React.createElement(Nav, {color:"blue"});
React + Redux @nikgraf
Rendering a Component
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return (<p>Hello World!</p>);
}
const exampleNode = document.getElementById('example');
ReactDOM.render(<App />, exampleNode);
main.js -> bundle.js
React + Redux @nikgraf
<body>
<div id="example">
<p> <!-- App start -->
Hello World!
</p> <!-- App end -->
</div>
</body>
index.html
Rendering a Component
React + Redux @nikgraf
Nested Components Part I
import React from 'react';
const Profile = ({avatar, name}) => {
return (
<div>
<img src={avatar} />
<span>{name}</span>
</div>
);
}
profile.js
React + Redux @nikgraf
import React from 'react';
import ReactDOM from 'react-dom';
import Profile from ‘./profile';
const App = () => {
return (
<div>
<h1>Hello World!</h1>
<Profile avatar="http://test.png" name="Nik" />
</div>
);
}
const exampleNode = document.getElementById('example');
ReactDOM.render(<App />, exampleNode);
main.js -> bundle.js
Nested Components Part II
React + Redux @nikgraf
<body>
<div id="example">
<div> <!-- App start -->
<h1>Hello World!</h1>
<div> <!-- Profile start -->
<img src="http://test.png" />
<span>Nik</span>
</div> <!-- Profile end -->
</div> <!-- App end -->
</div>
</body>
index.html
Nested Components Part III
React + Redux @nikgraf
Stateless Function Components
Functional Programming:
- avoid changing-state
- avoid mutable data
- calling a function twice with the same values as arguments will
produce the same result
Stateless Function Components:
- avoid changing-state
- avoid mutable data
- calling a function twice with the same values as arguments will
produce the same result
React + Redux @nikgraf
Wait, but why?
Predictable
easy to understand
&
easy to test
React + Redux @nikgraf
React + Redux @nikgraf
If/Else
const Profile = ({name, isOnline}) => {
let onlineIndicator;
if (isOnline) {
onlineIndicator = (<span>green</span>);
} else {
onlineIndicator = (<span>red</span>);
}
return (
<div>
{name} {onlineIndicator}
</div>
);
} profile.js
React + Redux @nikgraf
If/Else
<Profile name="Nik" isOnline={false}/>
<div>
Nik <span>red</span>
</div>
React + Redux @nikgraf
Loop
const FriendList = ({friends}) => {
return (
<ul>
{friends.map((friend) => {
return <li>{friend.name}</li>;
})}
</ul>
);
}
friendlist.js
React + Redux @nikgraf
Loop
const friends = [
{ name: 'Max'},
{ name: 'Tom'},
];
<FriendList friends={friends} />
<ul>
<li>Max</li>
<li>Tom</li>
</ul>
React + Redux @nikgraf
React Summary
- We can create out own components
- We can nest components as we like
- Stateless Function Components are pure
- We can control flow via JS (if, else, for, map …)
React + Redux @nikgraf
Interaction
const Profile = ({name}) => {
return (
<div>
{name}
<button onClick={ console.log('Clicked!'); }>
Click me!
</button>
</div>
);
}
profile.js
React + Redux @nikgraf
What to do with interactions like
onMouseOver,
onSubmit &
onClick?
React + Redux @nikgraf
Redux to rescue!
Redux allows you to manage the state with a
minimal API but completely predictable behaviour.
React + Redux @nikgraf
What about Flux?
Source: https://twitter.com/codecartoons/status/667348216669741056
React + Redux @nikgraf
Basic Principle
(previousState, action) => newState
React + Redux @nikgraf
React + Redux @nikgraf
Redux Flow
Store
Action
Creators
React
Components
Reducers
Interaction e.g onClick
dispatch(action)
(newState)
(state)
(previousState, action)
React + Redux @nikgraf
Feels like Fear just turned
into a Superpower
React + Redux @nikgraf
Action
const action = {
type: 'ADD_TODO',
text: 'Call Mom',
}
React + Redux @nikgraf
Action Creator
function addTodo(text) {
const trimmedText = text.trim();
return {
type: 'ADD_TODO',
text: trimmedText,
}
}
<button onClick={ dispatch(addTodo('Call Mom ') }>
Add Todo
</button>
actions.js
React + Redux @nikgraf
Reducer
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
text: action.text,
completed: false
}
]
default:
return state
}
} reducers.js
React + Redux @nikgraf
Store
import { createStore } from 'redux'
import todoReducer from '../reducers'
let store = createStore(todoReducer);
store.subscribe(() =>
console.log(store.getState())
)
store.dispatch(addTodo('Learn about reducers'));
store.dispatch(addTodo(‘Call Mom'));
React + Redux @nikgraf
Connect React with Redux
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import todoApp from './reducers';
import App from './containers/App';
let store = createStore(todoApp);
let exampleNode = document.getElementById('example');
ReactDOM.render(
<Provider store={store}><App /></Provider>,
exampleNode
);
React + Redux @nikgraf
Connect React +Redux
import React from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../actions.js';
const App = ({dispatch, state}) => {
return (
<button onClick={ dispatch(addTodo('Call Mom') }>
Add Todo
</button>
);
};
export default connect(App);
React + Redux @nikgraf
Redux Summary
- Redux allows you to manage the state with
predictable behaviour.
- (previousState, action) => newState
React + Redux @nikgraf
React + Redux @nikgraf
Time-travel Demo
React + Redux @nikgraf
Why this Stack?
- Reusable Components
- Predictable Code (functional)
- TimeTravel
- Performant & lightweight
React + Redux @nikgraf
Is it production ready?
React
- used by Facebook, Firefox, Airbnb and many more
Redux
- used by Firefox, Docker, Technical University of
Vienna, Mattermark and many more
- “Love what you’re doing with Redux”
Jing Chen, creator of Flux
Vienna React Meetup
Source: http://www.wolfography.at/
React + Redux @nikgraf
The End
Thanks for listening!
https://github.com/nikgraf
https://twitter.com/nikgraf
Vienna React Meetup
http://www.meetup.com/Vienna-ReactJS-Meetup/

More Related Content

What's hot

What's hot (20)

React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
 
React and redux
React and reduxReact and redux
React and redux
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
React js
React jsReact js
React js
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Reactjs
Reactjs Reactjs
Reactjs
 
React JS
React JSReact JS
React JS
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
ReactJS
ReactJSReactJS
ReactJS
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
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
 
React hooks
React hooksReact hooks
React hooks
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
Intro to React
Intro to ReactIntro to React
Intro to React
 

Viewers also liked

WordPress REST API + React + TypeScript
WordPress REST API + React + TypeScriptWordPress REST API + React + TypeScript
WordPress REST API + React + TypeScriptBorek Bernard
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
RxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingRxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingJay Phelps
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins Udaya Kumar
 

Viewers also liked (7)

WordPress REST API + React + TypeScript
WordPress REST API + React + TypeScriptWordPress REST API + React + TypeScript
WordPress REST API + React + TypeScript
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
 
RxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingRxJS + Redux + React = Amazing
RxJS + Redux + React = Amazing
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins
 

Similar to React + Redux Introduction

Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and SymfonyIgnacio Martín
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Luciano Mammino
 
Introduction to ReactJS and Redux
Introduction to ReactJS and ReduxIntroduction to ReactJS and Redux
Introduction to ReactJS and ReduxBoris Dinkevich
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobXAnjali Chawla
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs[T]echdencias
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Elyse Kolker Gordon
 
reactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfreactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfAyanSarkar78
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React PerformanceChing Ting Wu
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend DevelopersSergio Nakamura
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today Nitin Tyagi
 
Neoito — React 101
Neoito — React 101Neoito — React 101
Neoito — React 101Neoito
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тягаVitebsk Miniq
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projectsIgnacio Martín
 

Similar to React + Redux Introduction (20)

Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
Introduction to ReactJS and Redux
Introduction to ReactJS and ReduxIntroduction to ReactJS and Redux
Introduction to ReactJS and Redux
 
React outbox
React outboxReact outbox
React outbox
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobX
 
React redux
React reduxReact redux
React redux
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017
 
reactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfreactjs-quiz..docs.pdf
reactjs-quiz..docs.pdf
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
 
React lecture
React lectureReact lecture
React lecture
 
Lec9Handout.ppt
Lec9Handout.pptLec9Handout.ppt
Lec9Handout.ppt
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
Neoito — React 101
Neoito — React 101Neoito — React 101
Neoito — React 101
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 

More from Nikolaus Graf

Type Systems & Props Design - Exploring PropTypes, TypeScript, Flow & Reason
Type Systems & Props Design - Exploring PropTypes, TypeScript, Flow & ReasonType Systems & Props Design - Exploring PropTypes, TypeScript, Flow & Reason
Type Systems & Props Design - Exploring PropTypes, TypeScript, Flow & ReasonNikolaus Graf
 
Get started with Reason
Get started with ReasonGet started with Reason
Get started with ReasonNikolaus Graf
 
Introduction to Serverless
Introduction to ServerlessIntroduction to Serverless
Introduction to ServerlessNikolaus Graf
 
Serverless Framework Intro
Serverless Framework IntroServerless Framework Intro
Serverless Framework IntroNikolaus Graf
 
Rich text editing with Draft.js
Rich text editing with Draft.jsRich text editing with Draft.js
Rich text editing with Draft.jsNikolaus Graf
 
AngularDart Introduction
AngularDart IntroductionAngularDart Introduction
AngularDart IntroductionNikolaus Graf
 

More from Nikolaus Graf (10)

Type Systems & Props Design - Exploring PropTypes, TypeScript, Flow & Reason
Type Systems & Props Design - Exploring PropTypes, TypeScript, Flow & ReasonType Systems & Props Design - Exploring PropTypes, TypeScript, Flow & Reason
Type Systems & Props Design - Exploring PropTypes, TypeScript, Flow & Reason
 
Reason and GraphQL
Reason and GraphQLReason and GraphQL
Reason and GraphQL
 
Get started with Reason
Get started with ReasonGet started with Reason
Get started with Reason
 
Introduction to Serverless
Introduction to ServerlessIntroduction to Serverless
Introduction to Serverless
 
Serverless Framework Intro
Serverless Framework IntroServerless Framework Intro
Serverless Framework Intro
 
Rich text editing with Draft.js
Rich text editing with Draft.jsRich text editing with Draft.js
Rich text editing with Draft.js
 
Redux Universal
Redux UniversalRedux Universal
Redux Universal
 
React on es6+
React on es6+React on es6+
React on es6+
 
AngularDart Introduction
AngularDart IntroductionAngularDart Introduction
AngularDart Introduction
 
Web Components
Web ComponentsWeb Components
Web Components
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

React + Redux Introduction

  • 2. React + Redux @nikgraf Nik Graf @nikgraf nik@nikgraf.com Creator of Belle (UI Components) Working with StarterSquad Travelled around the World
  • 3. React + Redux @nikgraf ECMAScript2015 const sum = (first, second) => { return first + second; }
  • 4. React + Redux @nikgraf Created by Sebastian McKenzie - ECMAScript 2015 Support, JSX Support - Widely adopted
  • 5. Let’s get started Source: https://www.flickr.com/photos/mike52ad/
  • 6. React + Redux @nikgraf React React is a JavaScript Library for building user interfaces. • Focus on the UI, not a Framework • One-way reactive data flow (no two-way data binding) • Virtual DOM
  • 7. React + Redux @nikgraf Virtual DOM Keep track of state in DOM is hard. The DOM API is slow. (Try to re-render the whole DOM on every change)
  • 8. React + Redux @nikgraf Virtual DOM Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
  • 9. React + Redux @nikgraf Virtual DOM Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
  • 10. React + Redux @nikgraf Virtual DOM Benefits Batched DOM read/write operations. Efficient update of sub-tree only.
  • 11. React + Redux @nikgraf Our first Experiment Part I <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="bundle.js"></script> </head> <body> <div id="example"></div> </body> </html> index.html
  • 12. React + Redux @nikgraf Our first Experiment Part II import React from 'react'; import ReactDOM from 'react-dom'; const exampleElement = document.getElementById('example'); ReactDOM.render(<h1>Hello, world!</h1>, exampleElement); main.js -> bundle.js
  • 13. React + Redux @nikgraf JSX JSX is a JavaScript syntax extension that looks similar to XML. // Input (JSX): var app = <Nav color="blue" />; // Output (JS): var app = React.createElement(Nav, {color:"blue"});
  • 14. React + Redux @nikgraf Rendering a Component import React from 'react'; import ReactDOM from 'react-dom'; const App = () => { return (<p>Hello World!</p>); } const exampleNode = document.getElementById('example'); ReactDOM.render(<App />, exampleNode); main.js -> bundle.js
  • 15. React + Redux @nikgraf <body> <div id="example"> <p> <!-- App start --> Hello World! </p> <!-- App end --> </div> </body> index.html Rendering a Component
  • 16. React + Redux @nikgraf Nested Components Part I import React from 'react'; const Profile = ({avatar, name}) => { return ( <div> <img src={avatar} /> <span>{name}</span> </div> ); } profile.js
  • 17. React + Redux @nikgraf import React from 'react'; import ReactDOM from 'react-dom'; import Profile from ‘./profile'; const App = () => { return ( <div> <h1>Hello World!</h1> <Profile avatar="http://test.png" name="Nik" /> </div> ); } const exampleNode = document.getElementById('example'); ReactDOM.render(<App />, exampleNode); main.js -> bundle.js Nested Components Part II
  • 18. React + Redux @nikgraf <body> <div id="example"> <div> <!-- App start --> <h1>Hello World!</h1> <div> <!-- Profile start --> <img src="http://test.png" /> <span>Nik</span> </div> <!-- Profile end --> </div> <!-- App end --> </div> </body> index.html Nested Components Part III
  • 19. React + Redux @nikgraf Stateless Function Components Functional Programming: - avoid changing-state - avoid mutable data - calling a function twice with the same values as arguments will produce the same result Stateless Function Components: - avoid changing-state - avoid mutable data - calling a function twice with the same values as arguments will produce the same result
  • 20. React + Redux @nikgraf Wait, but why? Predictable easy to understand & easy to test
  • 21. React + Redux @nikgraf
  • 22. React + Redux @nikgraf If/Else const Profile = ({name, isOnline}) => { let onlineIndicator; if (isOnline) { onlineIndicator = (<span>green</span>); } else { onlineIndicator = (<span>red</span>); } return ( <div> {name} {onlineIndicator} </div> ); } profile.js
  • 23. React + Redux @nikgraf If/Else <Profile name="Nik" isOnline={false}/> <div> Nik <span>red</span> </div>
  • 24. React + Redux @nikgraf Loop const FriendList = ({friends}) => { return ( <ul> {friends.map((friend) => { return <li>{friend.name}</li>; })} </ul> ); } friendlist.js
  • 25. React + Redux @nikgraf Loop const friends = [ { name: 'Max'}, { name: 'Tom'}, ]; <FriendList friends={friends} /> <ul> <li>Max</li> <li>Tom</li> </ul>
  • 26. React + Redux @nikgraf React Summary - We can create out own components - We can nest components as we like - Stateless Function Components are pure - We can control flow via JS (if, else, for, map …)
  • 27. React + Redux @nikgraf Interaction const Profile = ({name}) => { return ( <div> {name} <button onClick={ console.log('Clicked!'); }> Click me! </button> </div> ); } profile.js
  • 28. React + Redux @nikgraf What to do with interactions like onMouseOver, onSubmit & onClick?
  • 29. React + Redux @nikgraf Redux to rescue! Redux allows you to manage the state with a minimal API but completely predictable behaviour.
  • 30. React + Redux @nikgraf What about Flux? Source: https://twitter.com/codecartoons/status/667348216669741056
  • 31. React + Redux @nikgraf Basic Principle (previousState, action) => newState
  • 32. React + Redux @nikgraf
  • 33. React + Redux @nikgraf Redux Flow Store Action Creators React Components Reducers Interaction e.g onClick dispatch(action) (newState) (state) (previousState, action)
  • 34. React + Redux @nikgraf Feels like Fear just turned into a Superpower
  • 35. React + Redux @nikgraf Action const action = { type: 'ADD_TODO', text: 'Call Mom', }
  • 36. React + Redux @nikgraf Action Creator function addTodo(text) { const trimmedText = text.trim(); return { type: 'ADD_TODO', text: trimmedText, } } <button onClick={ dispatch(addTodo('Call Mom ') }> Add Todo </button> actions.js
  • 37. React + Redux @nikgraf Reducer const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, { text: action.text, completed: false } ] default: return state } } reducers.js
  • 38. React + Redux @nikgraf Store import { createStore } from 'redux' import todoReducer from '../reducers' let store = createStore(todoReducer); store.subscribe(() => console.log(store.getState()) ) store.dispatch(addTodo('Learn about reducers')); store.dispatch(addTodo(‘Call Mom'));
  • 39. React + Redux @nikgraf Connect React with Redux import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import todoApp from './reducers'; import App from './containers/App'; let store = createStore(todoApp); let exampleNode = document.getElementById('example'); ReactDOM.render( <Provider store={store}><App /></Provider>, exampleNode );
  • 40. React + Redux @nikgraf Connect React +Redux import React from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions.js'; const App = ({dispatch, state}) => { return ( <button onClick={ dispatch(addTodo('Call Mom') }> Add Todo </button> ); }; export default connect(App);
  • 41. React + Redux @nikgraf Redux Summary - Redux allows you to manage the state with predictable behaviour. - (previousState, action) => newState
  • 42. React + Redux @nikgraf
  • 43. React + Redux @nikgraf Time-travel Demo
  • 44. React + Redux @nikgraf Why this Stack? - Reusable Components - Predictable Code (functional) - TimeTravel - Performant & lightweight
  • 45. React + Redux @nikgraf Is it production ready? React - used by Facebook, Firefox, Airbnb and many more Redux - used by Firefox, Docker, Technical University of Vienna, Mattermark and many more - “Love what you’re doing with Redux” Jing Chen, creator of Flux
  • 46. Vienna React Meetup Source: http://www.wolfography.at/
  • 47. React + Redux @nikgraf The End Thanks for listening! https://github.com/nikgraf https://twitter.com/nikgraf Vienna React Meetup http://www.meetup.com/Vienna-ReactJS-Meetup/

Editor's Notes

  1. Hello everybody, I'm Nik and today I will tell you about React in combination with Redux.
  2. A brief heads up what I do: Creator of Belle - React UI Components with over 1000 Github stars I'm Member & Team Lead of a freelancer community called StarterSquad. There we form teams to work with Startups and Science projects. As the teams I'm working with are spread over the globe I have the chance to travel a lot.
  3. I need to warn you upfront. In the code examples I will use ES20 15 syntax which got approved a few months back. This is a function all with 2 arguments. It creates the sum of them and returns the value. As you can see we assign it to a variable. const is a one-time assignable block scoped binding construct.
  4. And while browsers don't implement it yet we already can use it because compilers like Babel can compile it to EcmaScript5. The version that runs in the Browser of all your customers.
  5. * Who of you ever has built something with React? * Who of you considers to use if for your next React?
  6. Significant features of react: - It's a UI Library. It is not a full fleshed front-end framework. There is no routing, no data fetching. - One-way reactive data flow! You can't change data of parent. WHAT? Sound like a basic templating language.
  7. Manual DOM manipulation is messy and keeping track of the previous DOM state is hard. A solution to this problem is to write your code as if you were recreating the entire DOM whenever state changes. Of course, if you actually recreated the entire DOM every time your application state changed, your app would be very slow and your input fields would lose focus.
  8. React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.
  9. So when something happens in your data model React will figure out the diff and just update the necessary changes in the real DOM
  10. This gives us: Batched DOM read/write operations. Efficient update of sub-tree only.
  11. This is our index.html file. Nothing fancy. We load a script called bundle.js - it’s our compiled output from Babel. In addition with have one div with the ID example
  12. Here we have our main.js which is compiled to bundle.js What we do here is to render a headline with Hello World! We get the div with id example and use ReactDOM to render our headline into it. You might have 2 remarks here: why ReactDOM? Because we have different rendering targets. There is ReactCanvac, ReactNative and so on The second remark is probably: what the hack are you doing with html in JavaScript. That doesn’t work
  13. JSX is compiled with babel and allows us to simply use a XML like syntax in JS code simply for convenience. What about best practices of not mixing html & js. Well I’m sorry to tell, but that’s not the case anymore for React.
  14. Ok, done with the basics. Let’s get to some interesting things. Let us create a component that can used. We can create a component by just returning JSX from a function. Voila we have a component. We now can use this component.
  15. This is the output :) Pretty simple (go back)
  16. Let’s render dynamic content in a component by providing parameters. You can see here we create a profile component. The first argument of a component is always the properties. We can deconstruct them directly and use in our JSX code. Here we provide the avatar as a src for the image and the name is rendered directly into a span.
  17. Now we can import an use our component and use it anywhere else in JSX code. Here we use it inside a div. and we pass in the parameters it expects. Then we render the whole thing again
  18. Here I marked where the App component starts and end as well as where the Profile component starts and ends
  19. What I have shown you until now is actually pretty new. These function declarations are called stateless function components. There is a Component class in React as well that can have state, but you should use it carefully. Certain traits of function programming. Oh, it looks the same!
  20. Because it makes our code predictable and this leads to code that is easy to understand & and easy to test as well.
  21. So I hope by now you should be in this state!
  22. Of course we want to control the flow as well. So we can do if/else simply with js. Based on the isOnline parameters we assign onlineIndicator different html code. If the isOnline parameter changes the html output will change.
  23. Of course you can loop as well. Here we simply iterate over all the friends and return a list element for each of them.
  24. On things is missing! Interactions by the user. We provide the interaction callback as parameter to the button tag.
  25. But what do with these interactions? How can we change the parameters passed down to these components and actually create an effect?
  26. Redux for rescue
  27. Well, you might heard of Flux. It’s this application concept developed by Facebook which works well with React. From Flux we evolved into two directions: Redux & Relay
  28. Interestingly since quite some time in Web Development we learned to keep the data in one place. We don't store our data somewhere in memory or code. No, we have a database and when you do a request the application runs and gives you back a response. It's like a big function. Redux follows the same principle. It has one central place for your complete app state. That right now might scare the hell out of you.
  29. What is this guy talking? are you crazy? you want to keep all the app state in one object? Don't worry, it all will be fine.
  30. Let me give you a brief overview about how it works. The core of redux its the store instance. It is responsible to for keeping the application state. As you can see here the store provides the state to our react components and they render accordingly. When the user triggers an interaction like she clicks on a button we dispatch an actions. This action is passed to the reducers which create a new application state and return it to the store. That again influences the rendering. The cycle is complete.
  31. ideally that felt you have superpower. to be honest it took ma bit of time to get why the concept is great & important
  32. Let’s look at the building blocks. How does the code look like. First we have actions. Pretty simple just an JS object. The only thing important is that an action must have a type. Data is optional.
  33. We use action creators to create these actions an ideally do something with the data. API calls also come here.
  34. In the reducers we get the state passed in and then depending on the action type we manipulate the data. Get from one state to the next. Think about we reducing the passed state + the action to the new state. In this case we simply create a new arrays with the an action appended to it. By default it is marked as not completed. You can see we leverage the text of the actions here.
  35. The last pice in the puzzle is the store. It is initialised with the reducers. In our case the todo You can subscribe to it and when you dispatch a new action it will inform the subscribers.
  36. To make it work we need to wrap our App with a custom Provider component.
  37. To connect the store with our react components we wrap our root App component with a connect. Then you get the dispatch function from the store + state. To be honest that’s a bit of magic I don’t want to dive into too deep, but it works like a charm.
  38. Because of
  39. Ok, but why all the hassle with the actions and reducers? One single entry point for changes + timetravel
  40. Speakers like Christopher Pojer who is in Facebooks JavaScript Infrustructure Team (5 people).
  41. Thanks for listening Feel free to ask me any questions