React.js
- DURGESH VAISHNAV
ECMAScript 6 (ES6)
/ ECMAScript 2015 (ES2015)
const addition = (arg1, arg2) => arg1 + arg2;
OR
const addition = (arg1, arg2) => {
return arg1 + arg2;
}
More ….
 Block scope
– (let and const)
 Destructuring
- let [a, b] = [10, 20];
 Template String
let fullName = `${firstName} ${lastName}`
 Arrow function
let square = x => x * x;
What is React.js
 A java script library for building user interface. Render UI and responds to events.
 Declarative view for more predictable and easy to debug code.
 Component based for reusability.
 Building Components not templates
 Semantically, it is nothing but HTML and java script.
 Compare to other framework, it has full expressive power of java script.
Separation of Concerns
 Reduce coupling and increase cohesion.
 In Traditional MVC pattern, Controller, ModelView and View are coupled, when you
change one, you might need to change other.
Traditional Performance Best Practices
 Avoid expensive Document Object Model (DOM) operation
 Minimize access to the DOM
 Update elements offline before reinserting into the DOM
 Avoid tweaking HTML layouts in Java script
React Re-render
 React is using Virtual DOM to re-render every thing on every update.
 Not expensive, How?
 Create lightweight description of UI component.
 Diff it with the old one.
 Compute minimal set of changes to apply to the DOM.
 Batch execute all updates
 Benefit
 Clean
 Fast
How React Works
It is fast because it compute minimal DOM operation and batch read and
write.
App
State/
event
React
Component (UI)
Virtual DOM Compute DOM
operations Browser
Virtual DOM
Java script Extension (JSX)
 Initialization
 const element = <h1>Hello, world!</h1>;
 Embedding Expression
 const element = ( <h1> Hello, {formatName(user)}! </h1> );
 const element = <img src={user.avatarUrl}></img>;
 Child Node
 const element
= (<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div> );
 (Tip) Must use capitalized variable for Type at Runtime
function Story(props) {
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}
Props vs State
 Both props and state are plain JS objects
 Both props and state changes trigger a render update
 Both props and state are deterministic
 Props are a component configuration and it’s options, but state starts with
default value when component mounts.
 Props are immutable but state suffer from mutation in time (from user
events)
 Component always receive Props but manage their own state.
Stateful component
 Do not modify state directly
 // Wrong
this.state.comment = 'Hello';
 // Correct
 this.setState({comment: 'Hello'});
 State updates may be asynchronous, so use prevState
 // Wrong
this.setState({ counter: this.state.counter + this.props.increment, });
 // Correct
this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
 State updates are merged into default state.
fetchPosts().then(response => { this.setState({ posts: response.posts }); });
fetchComments().then(response => { this.setState({ comments: response.comments });
 The data flows down (parent component -> child component), so state can be pass to
child component as props
Containment/Nested Component
function FancyBorder(props) {
return ( <div className={'FancyBorder FancyBorder-' + props.color}> {props.children} </div> );
}
function WelcomeDialog() {
return ( <FancyBorder color="blue">
<h1 className="Dialog-title"> Welcome </h1>
<p className="Dialog-message"> Thank you for visiting our spacecraft! </p>
</FancyBorder> );
}
Here anything inside the <FancyBorder> JSX tag (h1 and p) gets passed into the
FancyBorder component as a children prop. Since FancyBorder renders {props.children}
inside a <div>, the passed elements appear in the final output.
If/Else
const Grade = ({marks} => {
let level;
if(marks > 90) {
level = (<span>A</span>);
} else {
level = (<span>B</span>);
}
return (<div>{level}</div>);
})
<Grade marks={94}/>
Loop
const CountryNames = ({countries} => {
return (<ul>
{countries.map((country) => {
return <li>{country.name}</li>;
})}
</ul>);
})
const countries = [{name: ‘USA’, name: ‘India’}] ;
<CountryNames countries={countries} />
Thinking In React
 Start with UI Mock and Break up UI into a Component Hierarchy, Try out
single responsibility principle, that is, a component should ideally only do
one thing. If it ends up growing, it should be decomposed into smaller
subcomponents.
 Build a static (Dump) version in React
 Identify The Minimal (but complete) Representation Of UI State,
Rules
 All React components must act like pure functions with respect to their
props.
 User-Defined Components Must Be Capitalized
 React Must Be in Scope (Import before using)
 Consider DRY: Don't Repeat Yourself.
What is Redux?
 Redux is a predictable state container for JavaScript apps
 Or Redux allows you to manage the state with a minimal API but
completely predictable behavior.
 Basic Idea
 (prevState, action) => newState
Three Principles of Redux
 Single source of truth - The state of your whole application is stored in an
object tree within a single store.
 State is read-only - The only way to change the state is to emit an action,
an object describing what happened.
 Changes are made with pure functions - To specify how the state tree is
transformed by actions, you write pure reducers.
How Redux Works
Actions/Action Creator
 Actions are payloads of information that send data from your application
to your store.
const ADD_TODO = 'ADD_TODO'
 Action creators are exactly that—functions that create actions.
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
Reducers
 Reducers specify how the application’s state changes in response with
some action happend.
 (previousState, action) => newState
 Reducer functions are called by the “Container” containers when there is a
user action
 If the reducer changes the state, Redux passes the new state to each
component and React re-renders each component
Store
The Store is the object that brings actions and reducers together. The store
has the following responsibilities:
 Holds application state;
 Allows access to state via getState();
 Allows state to be updated via dispatch(action);
 Registers listeners via subscribe(listener);
 Handles unregistering of listeners via the function returned by
subscribe(listener).
How to use Redux
 List State and Actions for each React Component
 Create Action Creators for each action
 Write Reducers for each Action
 Create Container Component for selected Component
 And defined Store to hold application state and attached all togather.
React Developer Tool
Installation
 npm install -g create-react-app
 create-react-app hello-world
 cd hello-world
 npm start
Question?
Thank you

React/Redux

  • 1.
  • 2.
    ECMAScript 6 (ES6) /ECMAScript 2015 (ES2015) const addition = (arg1, arg2) => arg1 + arg2; OR const addition = (arg1, arg2) => { return arg1 + arg2; }
  • 3.
    More ….  Blockscope – (let and const)  Destructuring - let [a, b] = [10, 20];  Template String let fullName = `${firstName} ${lastName}`  Arrow function let square = x => x * x;
  • 4.
    What is React.js A java script library for building user interface. Render UI and responds to events.  Declarative view for more predictable and easy to debug code.  Component based for reusability.  Building Components not templates  Semantically, it is nothing but HTML and java script.  Compare to other framework, it has full expressive power of java script.
  • 5.
    Separation of Concerns Reduce coupling and increase cohesion.  In Traditional MVC pattern, Controller, ModelView and View are coupled, when you change one, you might need to change other.
  • 6.
    Traditional Performance BestPractices  Avoid expensive Document Object Model (DOM) operation  Minimize access to the DOM  Update elements offline before reinserting into the DOM  Avoid tweaking HTML layouts in Java script
  • 7.
    React Re-render  Reactis using Virtual DOM to re-render every thing on every update.  Not expensive, How?  Create lightweight description of UI component.  Diff it with the old one.  Compute minimal set of changes to apply to the DOM.  Batch execute all updates  Benefit  Clean  Fast
  • 8.
    How React Works Itis fast because it compute minimal DOM operation and batch read and write. App State/ event React Component (UI) Virtual DOM Compute DOM operations Browser
  • 9.
  • 10.
    Java script Extension(JSX)  Initialization  const element = <h1>Hello, world!</h1>;  Embedding Expression  const element = ( <h1> Hello, {formatName(user)}! </h1> );  const element = <img src={user.avatarUrl}></img>;  Child Node  const element = (<div> <h1>Hello!</h1> <h2>Good to see you here.</h2> </div> );  (Tip) Must use capitalized variable for Type at Runtime function Story(props) { const SpecificStory = components[props.storyType]; return <SpecificStory story={props.story} />; }
  • 11.
    Props vs State Both props and state are plain JS objects  Both props and state changes trigger a render update  Both props and state are deterministic  Props are a component configuration and it’s options, but state starts with default value when component mounts.  Props are immutable but state suffer from mutation in time (from user events)  Component always receive Props but manage their own state.
  • 12.
    Stateful component  Donot modify state directly  // Wrong this.state.comment = 'Hello';  // Correct  this.setState({comment: 'Hello'});  State updates may be asynchronous, so use prevState  // Wrong this.setState({ counter: this.state.counter + this.props.increment, });  // Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));  State updates are merged into default state. fetchPosts().then(response => { this.setState({ posts: response.posts }); }); fetchComments().then(response => { this.setState({ comments: response.comments });  The data flows down (parent component -> child component), so state can be pass to child component as props
  • 13.
    Containment/Nested Component function FancyBorder(props){ return ( <div className={'FancyBorder FancyBorder-' + props.color}> {props.children} </div> ); } function WelcomeDialog() { return ( <FancyBorder color="blue"> <h1 className="Dialog-title"> Welcome </h1> <p className="Dialog-message"> Thank you for visiting our spacecraft! </p> </FancyBorder> ); } Here anything inside the <FancyBorder> JSX tag (h1 and p) gets passed into the FancyBorder component as a children prop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.
  • 14.
    If/Else const Grade =({marks} => { let level; if(marks > 90) { level = (<span>A</span>); } else { level = (<span>B</span>); } return (<div>{level}</div>); }) <Grade marks={94}/>
  • 15.
    Loop const CountryNames =({countries} => { return (<ul> {countries.map((country) => { return <li>{country.name}</li>; })} </ul>); }) const countries = [{name: ‘USA’, name: ‘India’}] ; <CountryNames countries={countries} />
  • 16.
    Thinking In React Start with UI Mock and Break up UI into a Component Hierarchy, Try out single responsibility principle, that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.  Build a static (Dump) version in React  Identify The Minimal (but complete) Representation Of UI State,
  • 17.
    Rules  All Reactcomponents must act like pure functions with respect to their props.  User-Defined Components Must Be Capitalized  React Must Be in Scope (Import before using)  Consider DRY: Don't Repeat Yourself.
  • 18.
    What is Redux? Redux is a predictable state container for JavaScript apps  Or Redux allows you to manage the state with a minimal API but completely predictable behavior.  Basic Idea  (prevState, action) => newState
  • 19.
    Three Principles ofRedux  Single source of truth - The state of your whole application is stored in an object tree within a single store.  State is read-only - The only way to change the state is to emit an action, an object describing what happened.  Changes are made with pure functions - To specify how the state tree is transformed by actions, you write pure reducers.
  • 20.
  • 21.
    Actions/Action Creator  Actionsare payloads of information that send data from your application to your store. const ADD_TODO = 'ADD_TODO'  Action creators are exactly that—functions that create actions. function addTodo(text) { return { type: ADD_TODO, text } }
  • 22.
    Reducers  Reducers specifyhow the application’s state changes in response with some action happend.  (previousState, action) => newState  Reducer functions are called by the “Container” containers when there is a user action  If the reducer changes the state, Redux passes the new state to each component and React re-renders each component
  • 23.
    Store The Store isthe object that brings actions and reducers together. The store has the following responsibilities:  Holds application state;  Allows access to state via getState();  Allows state to be updated via dispatch(action);  Registers listeners via subscribe(listener);  Handles unregistering of listeners via the function returned by subscribe(listener).
  • 24.
    How to useRedux  List State and Actions for each React Component  Create Action Creators for each action  Write Reducers for each Action  Create Container Component for selected Component  And defined Store to hold application state and attached all togather.
  • 25.
  • 26.
    Installation  npm install-g create-react-app  create-react-app hello-world  cd hello-world  npm start
  • 27.

Editor's Notes

  • #3 https://ponyfoo.com/articles/es6 https://github.deere.com/deere-ui/web-standards
  • #6 Coupling – The degree to which each program module relies on each of the other modules. Cohesion – The degree to which each element of modules belong together.
  • #14 JSX children passing as props
  • #26 Chrome plugin