Introduction


  • React is
    • Open source, maintained by Facebook
    • JS library for creating UI
      • Can be seen as V in MVC
      • React is a view layer library, not a framework like Backbone, Angular etc.
      • You can't use React to build a fully-functional web app
    • Ideal for large scale single page application
    • Uses a high speed VirtualDOM
    • Uses clean and easy to understand JSX syntax

Why was React developed?



  • Complexity of two-way data binding
  • Bad UX from using "cascading updates" of DOM tree
  • A lot of data on a page changing over time
  • Complexity of Facebook's UI architecture

Who uses React?

JS Engine


NodeJS Ecosystem


Important NPM Commands

  • npm init : NPM Initialize Command Creates a package.json file in our directory. Use -g for global install
  • npm install : Installs a package in the package.json file in the local node_modules folder.
  • npm uninstall : Remove a package from the package.json file and removes the module from the local node_modules folder.
  • npm update : This command updates the specified package. If no package is specified then it updates all the packages in the specified location.
  • npm start : Runs a command that is defined in the start property in the scripts.

Tools that we need

  • Package manager - npm
    • Lets you take advantage of a vast ecosystem of third-party packages, and easily install or update them.
  • Compiler- Babel
    • Lets you write modern JavaScript code that still works in older browsers.
  • Bundler- webpack or Reactify
    • Lets you write modular code and bundle it together into small packages to opeimize load time.
One single solution:

create-react-app
  • npx create-react-app my-app
  • cd my-app
  • npm start
DOM
  • Way of representing a structured document via objects
  • Compare it to a process being an instance of a program.
    • You can have multiple processes of the same one program
    • Just like you can have multiple DOMs of the same HTML
      • The same page loaded on many tabs
DOM-Issues
  • DOM is always tree-structured.
  • This is cool because we can traverse trees fairly easily.
    • Unfortunately, easily doesn’t mean quickly  here.
DOM-Issues

  • The main problem is that DOM was never optimized for creating dynamic UI.
  • Consider a DOM made of thousands of divs. Remember, we are modern web developers, our app is very SPA!
  • Try to move a 1000 divs 5 pixel left for example. It may take more than a second. It’s a lot of time for the modern web.
    • You can optimize the script and use some tricks, but in the end, it’s a pain to work with huge pages and dynamic UI.
Virtual DOM

  • It is lightweight and detached from the browser-specific implementation details.
  • Since the DOM itself was already an abstraction, the virtual DOM is, in fact, an abstraction of an abstraction.
  • Think of the virtual DOM as React’s local and simplified copy of the HTML DOM
    • Allows React to do its computations within this abstract world and skip the “real” DOM operations
Virtual DOM

On every update…

  1. React builds a new virtual DOM subtree
  2. diffs it with the old one
  3. computes the minimal set of DOM mutations and puts them in a queue
  4. and batch executes all updates

Introduction

  • React is fast.
    • Apps can handle complex updates and still feel quick and responsive.
  • React is modular.
    • Write many smaller, reusable files.
    • Solution to JavaScript's maintainability problems.
  • React is scalable.
    • Large programs that display a lot of changing data are where React performs best.
  • React is flexible.
    • You can use React for interesting projects that have nothing to do with making a web app.
  • React is popular.

React: the good

Easy to understand what a component will render

  • Declarative code → predictable code
  • You don't really need to study JS in the view file in order to understand what the file does

Easy to mix HTML and JS

  • You do it already with template libraries (e.g. Handlebars, Mustache, Underscore etc.)

Uses full power of JS

  • Decoupling templates from logic does not rely on the templates’ primitive abstractions, but uses full power of JavaScript in displaying views

No complex two-way data flow

  • Uses simple one-way reactive data flow
  • Easier to understand than two-way binding
  • Uses less code

React is fast!

  • Real DOM is slow
  • JavaScript is fast
  • Using virtual DOM objects enables fast batch updates to real DOM, with great productivity gains over frequent cascading updates of DOM tree

React dev tools

  • React Chrome extension makes debugging so much easier

Server-side rendering

  • React.renderToString() returns pure HTML

React: the bad

React is nothing but the view

  • No events
  • No XHR
  • No data / models
  • No promises / deferreds
  • No idea how to add all of the above

Very little info in the docs

  • But it's not hard to learn

Architectural annoyances

Building JSX requires some extra work

  • But most of the work is already done for you by react-tools

No support for older browsers

  • React won't work with IE8
  • There some polyfills / shims that help

Why should I use React?

Why should I use React?

  • Easy to read and understand views
  • Concept of components is the future of web development
  • If your page uses a lot of fast updating data or real time data - React is the way to go
  • Once you and your team is over the React's learning curve, developing your app will become a lot faster

Is switching to React easy?

Is switching to React easy?

Understanding how it works will take time and will slow you down at first (but once you and your team get it, things will start happening much faster)

Fundamentals

Most important terms in React

Component

Component


  • Components are self-contained reusable building blocks of web application.
  • React components are basically just idempotent functions (same input produces same output).
  • They describe your UI at any point in time, just like a server-rendered app.

Component

  • Created using class syntax
  • The only required method is render()
  • Inserted into DOM using ReactDOM.render()
					
import React, { Component } from 'react'
export default class Badge extends Component {
    render() {
        return (   
             
        )
    }
}
					
					

Props

Props

  • Passed down to component from parent component and represents data for the component
  • accessed via this.props
						
	render: function() {
	var someProp = 'bar';
					
	console.log('component render()', this.props);
				
	return <div>
	<AnotherComponent foo={someProp} model={this.props.model} />
	</div>;
	}
						
					

PropTypes

PropTypes
  • Runtime type checking for React props and similar objects.
  • You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.
  • Installation
    • npm install --save prop-types
  • Importing
    • import PropTypes from 'prop-types';
      var PropTypes = require('prop-types');
  • We can create proptypes like this:

State

State

  • Represents internal state of the component
  • Accessed via this.state
  • When a component's state data changes, the rendered markup will be updated by re-invoking render() method
						
render: function() {
	return <h3>Click count: 
	<span className='label label-default'>{this.state.clicks}</span>
	</h3>;
}				
					

JSX

JSX

  • Arguably, one of the coolest things in React
  • XML-like syntax for generating component's HTML
  • Easier to read and understand large DOM trees
  • Translates to plain JavaScript using react-tools
						
/** @jsx React.DOM */
render: function () {
	return <div>
		<h2><strong>Example 4:</strong>React App</h2>
		</div>;
}				
/** regular DOM */				
render: function () {
	return React.DOM.div(null, 
		React.DOM.h2(null, React.DOM.strong(null, "Example 4:"), " React App")
	);
}						
					

Virtual DOM

Virtual DOM

  • The virtual DOM is used for efficient re-rendering of the DOM
  • React aims to re-render the virtual tree only when the state changes
  • Uses 2 virtual trees (new and previous) to find differences and batch update real DOM
  • Observes data changes (setState) and does dirty-checking to know when to re-render component
  • Whenever possible, does not update entire component in real DOM - only computes a patch operation that updates part of the DOM

Examples

A simple component

A simple component

* see live example *

A nested component

A nested component

* see live example *

A stateful component

A stateful component

* see live example *

An app

An app

Hello World
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
	<h1>Hello, world!</h1>
	document.getElementById('title')
);
Introduction to JSX
  • JSX is a statically-typed, object-oriented programming language compiling to standalone JavaScript.
  • The first thing you'll notice is the XML-ish syntax in your JavaScript.
React without JSX
class SubjectList extends React.Component {
    render() {
        return
            React.createElement('div', {className: ‘subject-list'},
                React.createElement('h2', {}, ‘Subjects List for {this.props.name}’),
                React.createElement('ul', {},
                    React.createElement(‘li', {}, "Math") ,
                    React.createElement(‘li', {}, "English") ,
                    React.createElement(‘li', {}, "Javascript")
                );
            );
        }
   }

// Example usage: <SubjectList name=“Miley" />
React with JSX
class SubjectList extends React.Component {
    render() {
        return (
            <div className=‘subject-list’>
                <h2>Subjects List for {this.props.name}</h2>
                    <ul>
                        <li>Math</li>
                        <li>English</li>
                        <li>JavaScript</li>
                   </ul>
            </div>
        );
    }
}

// Example usage: < SubjectList name=“Miley" />

Life cycle

ReactElement

  • This is the primary type in React.
  • Light, stateless, immutable, virtual representation of a DOM Element.
  • Lives in the virtual DOM
    • Their immutability makes them easy and fast to compare and update. This is the reason of great React performance.
ReactElement
  • They are stateless, therefore don’t seem to be very helpful for the programmers

JSX compiles HTML tags to ReactElements:
var root = <div>hello world</div>; ReactDOM.render(root,document.getElementById('example'));.
ReactComponent

  • What differs ReactComponent from ReactElement is - ReactComponents are stateful.
var CommentBox = React.createClass({
	render: function() {
		return (
			<div className="commentBox">
				Hello, world! I am a CommentBox.
			</div>
		);
	}
});
Event Handling and Synthetic Events

  • With React you simply pass your event handler as a camelCased prop
  • React ensures that all events behave similarly in all browsers
    • by implementing a synthetic event system
  • Under the Hood
    • Autobinding
    • Event Delegation
Autobinding
  • When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of 'this' is correct.
var person = {firstName: ‘Black', lastName: ‘Mark'};

function say() {
    console.log('Hello ' + this.firstName + ' ' + this.lastName);
}

var sayHello = say.bind(person);

sayHello(); // Hello Black Mark
Event Delegation

  • React doesn't actually attach event handlers to the nodes themselves.
  • When React starts up
    • It starts listening for all events at the top level using a single event listener.
  • When a component is mounted or unmounted
    • the event handlers are simply added or removed from an internal mapping
  • When an event occurs, React knows how to dispatch it using this mapping
Separation of Concerns

  • By building modular components that reuse other components with well-defined interfaces
    • you get much of the same benefits that you get by using functions or classes
Example

var Panel = React.createClass({
	render: function(){
		return(
			<div>
			<Badge count=“33”/>
			<Image src=“someurl.com”/>
			</div>
		);
	}
})
Ownership
  • In the above example, instances of Panel own instances of Badge and Image
  • In React, an owner is the component that sets the props of other components
    • It is said that Badge is owned by Panel
    • A component cannot mutate its props they are always consistent with what its owner sets them to
Ownership
  • The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM
    • Panel owns the div, Badge and Image instances
    • <div> is the parent (but not owner) of the Badge and Image instances.
Children

<Parent><Child/></Parent>
  • Parent can read its children by accessing the special this.props.children prop..
  • this.props.children is an opaque data structure: use the React.Children utilities to manipulate them
Dynamic Children

render() {
    return (
      <ol>
        {this.props.results.map((result) => (
          <li key={result.id}>{result.text}</li>
        ))}
      </ol>
    );
  }
Data Flow
  • This is effectively one-way data binding:
    • owners bind their owned component's props to some value the owner has computed based on its props or state.
      • Since this process happens recursively, data changes are automatically reflected everywhere they are used
Communication between Components
  • The best approach would depend on how you plan to arrange those components
  • Example scenarios:
    • <Filters /> is a child component of <List />
    • <Filters /> and <List /> are siblings
    • <Filters /> and <List /> live in separate root components entirely
Reusable Components
  • Break down the common design elements (buttons, form fields, layout components, etc) into reusable components with well-defined interfaces.
  • The next time you need to build some UI you can write much less code
  • Which means
    • Faster development time
    • Fewer bugs
Cloning Components
  • In rare situations a component may want to change the props of a component that it doesn't own
    • Like changing the className of a component passed as this.props.children.
  • Other times it may want to make multiple copies of a component passed to it.
    • cloneWithProps()makes this possible.
ReactComponent React.addons.cloneWithProps(ReactComponent component,object?extraProps
Cloning Components
  • In rare situations a component may want to change the props of a component that it doesn't own
  • Other times it may want to make multiple copies of a component passed to it.
var clonedcomponent = cloneWithProps(
	originalComponent,
	{
		key: originalComponent.key
	}
);
Controlled Component
  • An <input> with value property is an controlled component
getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value:
	event.target.value});
  },
  render: function() {
    return (
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }
Uncontrolled Component
  • An <input> without value property is an uncontrolled component
render: function() {
	return <input type="text" />;
}
Component CSS

  • CSS pollutes the global namespace
    • This is bad because it leads to paralysis and confusion.
  • Inline styles avoid this, because the CSS is scoped to the component.
Component CSS

var Title = React.createClass({
	titleText: "Some text",

	render(){
	  var inlineCss = {
	     padding:'10px',
	     lineHeight:'16px',
	     color:'red'
	  }
	  return<div>
	  	<h1 style={inlineCss}>{titleText}</h1>
	  </div>
	}
})
Not really inline

  • Style is actually a much better name than class.
    • You want to “style” the element, not “class” it.
  • Finally, this is not applying the style directly, this is using React virtual DOM and is being diff-ed the same way elements are.
<h1 style={inlineCss}>{titleText}</h1>
Conditional Rendering
  • Conditional rendering in React works the same way conditions work in JavaScript.
  • Use JavaScript operators like  if or the conditional operator to create elements representing the current state, and let React update the UI to match them.
var Greeting  = React.createClass({
	const isLoggedIn = this.props.isLoggedIn;
		if (isLoggedIn) { return <UserGreeting />; }
		return <GuestGreeting />;
});
ReactDOM.render(
	<Greeting isLoggedIn={false} />,
	document.getElementById('root')
);
List
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number){
	return number*2;
});
console.log(doubled);
function NumberList(props) {
	const numbers = props.numbers;
	const listDoubledItems = numbers.map(function(number) {
		let num = number*2;
		return <li>{num}</li>
	});
	return ( <ul>{listDoubledItems}</ul> );
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
	<NumberList numbers={numbers} />,
		document.getElementById('root') );
List and Key
  • When you run above code, you'll be given a warning
    • A key should be provided for list items.
  • Let's assign a key to our list items inside numbers.map() and fix the missing key issue.
function NumberList(props) {
	const numbers = props.numbers;
	const listDoubledItems = numbers.map(function(number) {
		let num = number*2;
		return <li key={number.toString()}> {num} </li>
	});
	return ( <ul>{listDoubledItems}</ul> );
}
Key
  • Keys help React identify which items have changed, are added, or are removed.
  • Keys should be given to the elements inside the array to give the elements a stable identity:


const todoItems = todos.map((todo) =>
	<li key={todo.id}>
		{todo.text}
	</li>
);
const todoItems = todos.map((todo, index) =>
	<li key={index}>
		{todo.text}
	</li>
);
Form: Crucial & Complex

  • A form creates a cohesive, effective, and compelling data entry experience.
  • Forms seem straightforward:
    • you make an input tag
    • the user fills it out
    • and hits submit
  • How hard could it be?
Form
  • Form can end up being really complex
    • Form inputs are meant to modify data, both on the page and the server
    • Changes often need to be reflected elsewhere on the page
    • Users have a lot of leeway in what they enter, so you need to validate values
    • The UI needs to clearly state expectations and errors, if any
    • Dependent fields can have complex logic
    • We want to be able to test our forms, without relying on DOM selectors
Form
  • In most cases, it's convenient to have a JavaScript function that
    • Handles the submission of the form
    • Has access to the data that the user entered into the form.
  • <form>
    	Name: <input type="text" name="name" />
    
    	<input type="submit" value="Submit" />
    </form>
    
  • The standard way to achieve this is with a technique called "controlled components".
Routing

  • React does not have a native router
  • There are however a few to choose between
    • React-router
    • React-router-component
    • Monorouter
React-Router Example

// other imports
import { Router, Route, IndexRoute, hashHistory } from "react-router";

const app = document.getElementById('app');

ReactDOM.render(
    <Router history={hashHistory}>
          <Route path="/" component={Layout}>
                <IndexRoute component={Todos}></IndexRoute>
                <Route path="favorites" component={Favorites}></Route>
                <Route path="settings" component={Settings}></Route>
                <Route path="todos1" component={Todos1}></Route>
          </Route>
    </Router>,
app);
Server Rendering

  • Traditional JavaScript applications are hard to render on the server.
  • This makes the app uncrawlable, and you miss out on SEO.
  • Fortunately, React can handle this with ease.
Modules


  • A separate unit of application
  • Good modules are Highly self-contained with distinct functionality.
    • Allowing them to be shuffled, removed, or added as necessary
    • Without disrupting the system as a whole
JS modules

  • Encapsulation & Dependency
    • Different pieces of software are usually developed in isolation
    • Other pieces of software are brought into the project

Why Modules

  • Maintainability
    • Updating a single module is much easier when the module is decoupled from other pieces of code.
  • Namespacing
    • Modules allow us to avoid namespace pollution by creating a private space for our variables..
  • Reusability
    • Let’s be honest here: copy previously written code into new projects.
JS modules
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Backbone.js Todos</title>
        <link rel="stylesheet" href="todos.css"/>
    </head>
	<body>
        <script src="../../test/vendor/json2.js"></script>
        <script src="../../test/vendor/jquery.js"></script>
        <script src="../../test/vendor/underscore.js"></script>
        <script src="../../backbone.js"></script>
        <script src="../backbone.localStorage.js"></script>
        <script src="todos.js"></script>
    </body>
	<!-- (...) -->
</html>
JS modules

  • As JavaScript development gets more and more complex
    • Dependency management can get cumbersome.
    • Refactoring is also impaired
      • Where should newer dependencies be put to maintain proper order of the load chain?
  • JavaScript module systems attempt to deal with these problems
JS modules
  • This pattern has been in use for quite some time in JavaScript projects
    • Deals fairly nicely with the encapsulation matter
    • It does not do much about the dependencies issue
CommonJS modules
  • Synchronous, thus blocking
    • Generally understood to be an easier read.
  • Designed with server development in mind.
  • The dominant implementation of this standard is in Node.js
var a = require('module-a');
var b = require('module-b');

module.exports = {
func: function() {...},
integer: a.integer,
string: b.string;
};
CJS Modules

AMD Modules
  • Asynchronous Module Definition (AMD)
    • Accounts for the async nature of JS but some felt harder to read with a wrapper function.
    • The most popular implementation of this standard is RequireJS
define(['module-a', 'module-b'], function(a, b) {
return {
        func: function() {...},
        integer: a.integer,
        string: b.string;
    };
});
AMD Modules

ES6 Modules

  • Fortunately, the ECMA team behind the standardization of JavaScript decided to tackle the issues of modules.
  • The result is
    • ECMAScript 2015, ECMAScript 6, ES6
    • syntactically pleasing and compatible with both synchronous and asynchronous modes of operation.
ES6 Modules

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
ES6 Modules

Implementation
  • Unfortunately none of the major JavaScript runtimes support ES2015 modules in their current stable branches
    • No support in Firefox, Chrome or Node.js
  • Fortunately
    • Many transpilers do support modules
    • A polyfill is also available
    • Currently, the ES2015 preset for Babel can handle modules with no trouble.
    • System.js: a universal module loader that supports CommonJS, AMD and ES2015 modules
      • Can work in tandem with transpilers such as Babel, Traceur or Typescript?
      • Does all the job on-the-fly

Flux

  • An architecture
    • Facebook uses internally when working with React
  • Not a framework or a library
    • Design pattern
    • The concept of Unidirectional Data Flow

Flux-Individual Components

  • Actions
    • Helper methods that facilitate passing data to the Dispatcher
  • Dispatcher
    • Receives actions and broadcasts payloads to registered callbacks
  • Stores
    • Containers for application state & logic that have callbacks registered to the dispatcher
  • Controller Views
    • React Components that grab the state from Stores and pass it down via props to child components.
Flux-Individual Components
Flux-Individual Components

Dispatcher

  • The Dispatcher is basically the manager of entire process.
  • Receives actions and dispatches the actions and data to registered callbacks
Dispatcher

One dispatcher per application
import { Dispatcher } from 'flux';

export default new Dispatcher;
ActionCreators & Actions

  • Action Creators are collections of methods that are called within views to send actions to the Dispatcher.
  • Actions are the actual payloads that are delivered via the dispatcher.
import dispatcher from '../dispatcher';

export function createTodo(text, competed){
	dispatcher.dispatch({type:"CREATE_TODO", text: text, complete:completed});
}

export function deleteTodo(id){
	dispatcher.dispatch({type:"DELETE_TODO", id: id});
}
Stores

  • Stores manage application state for a particular domain within your application.
  • This basically means that per app section Stores manage
    • The data
    • Data retrieval methods
    • Dispatcher callbacks
Stores
import EventEmitter from 'events';
import dispatcher from '../dispatcher';

class TodoStore extends EventEmitter{
	constructor(){
		super();
		this.todos = [...]
	}
	getAllTodos(){
		return this.todos;
	}
	createTod(text, completed){
		let id=Date.now();
		this.todos.push({id: id, text, complete: completed});
		// this.emit("change");
	}
	updateTodo(){
		// this.emit("update");
	}
	handleAction(action){
		console.log(action);
		switch(acction.type){
			case 'CREATE_TODO': this>createTodo(action.text, action.complete);
				break;
		}
	}
}
var todoStore = new TodoStore;
dispatcher.register(todoStore.handleAction.bind(todoStore));
Stores
  • The most important thing we did above is to extend our store with NodeJS’s EventEmitter.
    • Allows our stores to listen/broadcast events.
    • Allows our Views/Components to update based upon those events
      • Because our Controller View listens to our Stores, leveraging this to emit change events will let our Controller View know that our application state has changed and its time to retrieve the state to keep things fresh.
Stores
  • We also registered a callback with our Dispatcher using its register method.
    • This means that our Store is now listening to Dispatcher broadcasts.
    • Our switch statement determines if there are any relevant actions to take.
    • If a relevant action is taken, a change event is emitted, and views that are listening for this event update their states.
Stores

Controller Views
  • Controller views are really just React components
    • That listen to change events and retrieve Application state from Stores.
    • Our switch statement determines if there are any relevant actions to take.
    • They then pass that data down to their child components via props.
Controller Views
import React from 'react';
import Todo from '../components/Todo';
import todoStore from '../store/TodoStore';
import * as TodoAction from '../action/TodoAction';

export default class Todos extends React.Component {
	constructor(){
		super();
		this.state = {
			todo: todoStore.getAllTodos()
		};
	}
	componentWillMount(){
		todoStore.on("change", ()=>{
			let todos = todoStore.gerAllTodos();
			this.setState({todos: todos});
		});
		todoStore.on("update", ()=>{
			console.log("update date...");
		});
	}
	createTodo(){
		let text = "Read Java";
		let complete = false;
		TodoAction.createTodo(text, complete);
	}
}
render() {
	const{ todos } = this.state;

	const TodoComponents = todos.map(todo) => {
		return <Todo key={todo.id} {...todo}/>;
	}

	return(
		<div>
			<h1>Todos</h1>
			<ul>{TodoComponents}</ul>

			<button onclick={this.createTodo.bind(this)}>Create Todo</button>
		</div>
	);
}
Putting It All Together
Redux
  • Redux is a pattern and library for managing and updating application state, using events called "actions".
  • Understand when, where, why, and how the state in your application is being updated
  • How your application logic will behave when those changes occur
React Key Concepts
  • Store:

    A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer.

  • Reducers:

    The Reducer function in the redux helps us to return the new app state by taking the previous app state and type of action.

  • The following few things should never be performed inside the reducer −

    1. Mutation of functions arguments
    2. API calls & routing logic
    3. Calling non-pure function e.g. Math.random()
  • Container:

    The container is the function (usually in a separate file) which gives the component props the special ability to interact with state.

  • Actions:

    Actions are the only source of information for the store. Actions have a type field that tells what kind of action to perform and all other fields contain information or data.

  • Providers:

    The Provide component makes the Redux store available to any nested components that need to access the Redux store.

When Should I Use Redux?
  • You have large amounts of application state that are needed in many places in the app
  • The app state is updated frequently over time
  • The logic to update that state may be complex
  • The app has a medium or large-sized codebase, and might be worked on by many people
Core Concepts
  • The state, the source of truth that drives our app;
  • The view, a declarative description of the UI based on the current state
  • The actions, the events that occur in the app based on user input, and trigger updates in the state
Redux Data Flow
  • Store
    • One single store for entire application
    • Store are created using createStore method syntax: redux.createStore(reducer)
  • Reducers
    • Modify the state depending on action
    • Don't directly modify the state
    • No side effects (http calls not allowed)
  • Dispatch
    • Dispatches actions to store, reaches reducer then
    • The only way to update the state is to call store.dispatch() and pass in an action object.

Redux MiddleWare

Middleware
  • Enhancers are powerful because they can override or replace any of the store's methods: dispatch, getState, and subscribe.
  • But, much of the time, we only need to customize how dispatch behaves. It would be nice if there was a way to add some customized behavior when dispatch runs.
  • Redux uses a special kind of addon called middleware to let us customize the dispatch function.
Implementing Middleware
  • Redux middleware are actually implemented on top of a very special store enhancer that comes built in with Redux, called applyMiddleware.
  • We'll start with applyMiddleware by itself, and we'll add three example middleware
  • Unlike a reducer, middleware can have side effects inside, including timeouts and other async logic.
Writing Custom Middleware
  • We can write our own middleware. You might not need to do this all the time, but custom middleware are a great way to add specific behaviors to a Redux application.
  • Redux middleware are written as a series of three nested functions
  • Because these are normal functions, we can also write them using ES6 arrow functions. This lets us write them shorter because arrow functions don't have to have a return statement, but it can also be a bit harder to read if you're not yet familiar with arrow functions and implicit returns.

    Here's the same example as above, using arrow functions:

Redux Thunk

Thunk Middleware
  • Redux already has an official version of that "async function middleware", called the Redux "Thunk" middleware. The thunk middleware allows us to write functions that get dispatch and getState as arguments. The thunk functions can have any async logic we want inside, and that logic can dispatch actions and read the store state as needed.

    Writing async logic as thunk functions allows us to reuse that logic without knowing what Redux store we're using ahead of time.

Configuring the Store
  • The Redux thunk middleware is available on NPM as a package called redux-thunk. We need to install that package to use it in our app:
  • Once it's installed, we can update the Redux store
  • Or if you want to add a design component in our React application, we can use Redux Thunk to set up middleware. To do this, we have modified the above code by including the HTML and CSS components as shown

RxJS

RxJS
  • RxJS is a JavaScript library that uses observables to work with reactive programming that deals with asynchronous data calls, callbacks and event-based programs.
  • Features of RxJS:
    • Observable :An observable is a function that creates an observer and attaches it to the source where values are expected, for example, clicks, mouse events from a dom element or an Http request, etc.

    • Observer :It is an object with next(), error() and complete() methods, that will get called when there is interaction to the with the observable i.e. the source interacts for an example button click, Http request, etc.

    • Subscription : A subject is an observable that can multicast i.e. talk to many observers. Consider a button with an event listener, the function attached to the event using addlistener is called every time the user clicks on the button similar functionality goes for subject too.

    • Operators : An operator is a pure function that takes in observable as input and the output is also an observable.

  • Features of RxJS:
    • Subject :A subject is an observable that can multicast i.e. talk to many observers. Consider a button with an event listener, the function attached to the event using addlistener is called every time the user clicks on the button similar functionality goes for subject too.

    • Schedulers :A scheduler controls the execution of when the subscription has to start and notified.

Best Practices
  1. Always define your propTypes.
  2. For any propType that isn't required, always set it in getDefaultProps.
  3. Rely on ...spreadSyntax over passing props explicity.
  4. Place your derived props or state in render() rather than in getInitialState().
  5. Use
    • JSX
    • ES6 (transpiled with Babel)
    • Webpack
Best Practices
  • Always look at your bundle size
    Bad=> import {Foo} from ‘foo’
    Good=> import Foo from ‘foo/Foo’
  • Keep your components small (Very Small)
  • Minimize your States
    • Avoid synchronizing state between a child and parent
  • Use ShouldComponentUpdate for performance optimization
Best Practices
  • Always bind the functions in the constructor
    export default class BindFunctionExample extends React.Component {
    	constructor() {
    		super();
    		this.state = {
    			hidden: true,
    		};
    		this.toggleHidden = this.toggleHidden.bind(this);
    	}
    
    	toggleHidden() {
        		const hidden = !this.state.hidden;
        		this.setState({hidden})
    	}
    	render(){
    		return(
    			<button onClick={this.toggleHidden} />
    		);
    	}
    }
    
  • Use Prop validation
    • PropTypes will make your life a lot better when working with a large team.
Best Practices
  • Use Redux/Flux
    • Flux/Redux allows you to handle data easily and takes the pain away from handling front end cache.
  • Avoid Refs
    • Refs will only make your code harder to maintain.
    • Plus when you use refs you are manipulating the virtual Dom directly.
    • Which means that the component will have to re-render the whole Dom tree.
Best Practices
file_structure_1
File structures with React/Redux that makes things easy to work with.
file_structure_2