REACT
how do you call al render method
React.DOM.render(< />, document.getElementById('app'))
when a react element is compiled it transforms into a what?
React.createElement() call
to reset game?
set to 0
node start in package json
"start": "node index.js"
express library
A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. const app = express() : start an instance of express http server .get, .post, .delete ,etc(route, onReq callback) - method for handling requests to routes Middleware - functions between req and res that have accress to both objects. Most popular: logging, CORS, file compression, csrf pretection, cookie sessions
libuv
A multi-platform support library with a focus on asynchronous I/O. Some of the features of libuv are: Full-featured event loop Asynchronous file and file system operations Child processes File system events
Component
A small, independent, reusable piece of UI. A function that returns a React element to be rendered to the DOM
Flux pattern
An architectural pattern that enforces unidirectional data flow — its core purpose is to control derived data so that multiple components can interact with that data without risking pollution. SOLVES: vanilla and jQuery MVC problem of poorly defined data flow and lack of data integrity (storing state in the DOM). The Flux pattern is generic; it's not specific to React applications, nor is it required to build a React app. However, Flux is commonly used by React developers because React components are declarative — the rendered UI (View) is simply a function of state (Store data). action -> dispatcher -> store -> view the Store is the central authority for all data; any mutations to the data must occur within the store. Changes to the Store data are subsequently broadcast to subscribing Views via events. Views then update themselves based on the new state of received data. To request changes to any Store data, Actions may be fired. These Actions are controlled by a central Dispatcher; Actions may not occur simultaneously, ensuring that a Store only mutates data once per Action.
Controlled component
An input form element whose value is controlled by React. When a user enters data into a controlled component, a change event handler is triggered and your code decides whether the input is valid (by re-rendering with the updated value). If you do not re-render then the form element will remain unchanged.
Redux Action
An object that describes the outcome of an event. Payload of information that sends data from your application to your store. The only source of information for the store.
What is React?
An open-source JavaScript library created by Facebook for building UI components for web and mobile. It has no opinions on the other pieces of your technology stack and can be seamlessly integrated into any application.
props
Inputs to a React component. Data passed down from a parent component to a child component. Props are readonly. They should not be modified in any way.
How does Node work?
It is single-threaded, and uses async callbacks and an event loop to perform tasks like fetching data or interacting with a DB
Webpack loaders
Loaders enable webpack to process more than just JavaScript files. They give you the ability to leverage webpack's bundling capabilities for all kinds of files by converting them to valid modules that webpack can process. Loaders transform all types of files into modules that can be included in your application's dependency graph (and eventually a bundle). in other words, makes it so you can import/require non-js files
what goes at the bottom of app.js usually
ReactDOM.render( <MyComponentClass />, document.getElementById('app') );
write ReactDOM.render
ReactDOM.render( <Owl />, document.getElementById('app') );
Redux Reducer
Reducers specify how the application's state changes in response to actions sent to the store. Reducer is a function that takes current state and action as arguments, returns new state. thus, state remains immutable
ref
Refs provide a way to access DOM nodes or React elements created in the render method, in the few cases where you need to imperatively modify a child outside of the typical dataflow: Managing focus, text selection, or media playback; Triggering imperative animations; Integrating with third-party DOM libraries. Avoid using refs for anything that can be done declaratively.
Webpack output
The output property tells webpack where to emit the bundles it creates and how to name these files, it defaults to ./dist. Basically, the entire app structure will get compiled into the folder that you specify in the output path.
Enzyme
Tool for testing React component output. Note that React provides its own testing utilities, but also recommends Enzyme and react-testing-library shallow(component) - constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components. mount(component) - Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs, or may require the full lifecycle in order to fully test the component (i.e., componentDidMount etc.) render() - used to render react components to static HTML and analyze the resulting HTML structure. find(selector) => wrapper (like jQuery) simulate(event)
diffing and reconciliation
When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one (diffing). When they are not equal, React will update the native DOM (reconciliation).
Webpack plugins
While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks. Plugins range from bundle optimization and minification all the way to defining environment-like variables. The plugin interface is extremely powerful and can be used to tackle a wide variety of tasks.
Uncontrolled component
Works like form elements do outside of React. When a user inputs data into a form field (an input box, dropdown, etc) the updated information is reflected without React needing to do anything. However, this also means that you can't force the field to have a certain value.
to make a component you do use what? And that is what?
a base class from the React library: React.Component a React.Component is a javascript class
every component must come from what?
a component class
steps to create context
at parent level, create MyContext with React.createContext() Create class MyProvider, set state inside the class, return MyContext.Provider (notice composition) MyProvider is equvalent of Redux store Wrap entire app in MyProvider Inside of component that needs access to context, create MyContext.Consumer component, and make its child a function that returns elements which can access the context!
import config from "./config" does what?
it turns config into a variable
Chaining
mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.
render is a what? and return is a what
render = method return = statement
when you render a component you need what 2 things
render function with class in < /> and getElementById function with app id from the HTML file
to change state
this.setState({})
Redux
A predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Most important features are single source of truth and enforcing of synchronous action handling. combineReducers({reducers}) - generates a function that calls your reducers with the slices of state selected according to their keys, and combining their results into a single object again. createStore(reducer) - self-explantory: creates store object
stateless component
A pure function that renders DOM object based solely on the properties (parameters) provided to it. No internal state, no lifecycle hooks
state is simply
A property of the component class. You can then access it via this.state in your class JSX code (which you return in the required render() method).
Redux Reducers
Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happened, but don't describe how the application's state changes.
What is redux?
Redux is a predictable state container for JavaScript apps.
payment request API
Rethinking the "shopping cart" metaphor for online shopping. Meant to eliminate checkout forms and standardize online payment process. browser, device, platform, and vendor agnostic. UI is provided by browser. ALl is handled by a single API call from server
what is a small reusable chunk of code that is usually used to render html
a component
props.children
anything inside the open close tag for the component.
Redux Actions
are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch(). Actions are plain JavaScript objects. Actions must have a type property that indicates the type of action being performed.
axios call
axios({ method: 'get', url: 'http://myapi-profstream.herokuapp.com/api/f4b493/wines', responseType: 'json' })
Redux Action Creators
functions that create actions. It's easy to conflate the terms "action" and "action creator", so do your best to use the proper term. In Redux, action creators simply return an action. To actually initiate a dispatch, pass the result to the dispatch() function. Alternatively, you can create a bound action creator that automatically dispatches:
Redux combineReducers()
generates a function that calls your reducers with the slices of state selected according to their keys, and combines their results into a single object again
Redux reducer composition,
gives it the slice of the state to manage, and knows how to update just that slice.
this.state is???
immutable
render a component
import React from 'react'; import ReactDOM from 'react-dom'; class MyComponentClass extends React.Component { render() { return <h1>Hello world</h1>; } }; ReactDOM.render( <MyComponentClass />, document.getElementById('app') );
Immutable
is a JavaScript library implementing persistent data structures. It is performant and has an idiomatic JavaScript API.
what do you have to add to jsx as an attribute usually for lists? When do you need this attribute?
keys The list-items have memory from one render to the next. For instance, when a to-do list renders, each item must "remember" whether it was checked off. The items shouldn't get amnesia when they render. A list's order might be shuffled. For instance, a list of search results might be shuffled from one render to the next.
Benefits of Node
low latency and high throughput- Non-blocking approach to serving requests means less time (and less memory) wasted waiting for I/O requests to resolve Built on V8, which is already super fast best for apps that are computationally simple, but high frequency of access
whenever you make a component. That component inherits all the ________________________
methods of it's component class
update webpack run
npm run build
empty object
null
synthetic event
objects which act as a cross-browser wrapper around the browser's native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.
What triggers React to re-render your components and potentially update the DOM in the browser
only changes in props and/ or state trigger React to re-render your components and potentially update the DOM in the browser
redux middleware
provides third-party extension between dispatching an action, and the moment it reaches the reducer. thunk - useful for making async API calls.
REPL
read, evaluate, print, loop
never set state inside
render
you can change state via 3 methods:
state, props and context.
what kind of component is this import React from 'react'
stateless component
to make your own component class you must?
subclass React.Component class COMPONENTNAME
static analysis
testing code without actually running it. E.G., linting, typescript typing
To make a React component, you write a JSX element. What do you name it?
the same as your component class
all methods are written inside?
the state method
redux dispatch
trigger a state change based on provided action type and payload
props lexical context
when props are utilized in a Class based component use: {this.props.expl} vs Functional component use: {props.expl}
to only change the state in the current file?
{this.xxxxxxxx.state.bind(this)}
how are class components written?
InUpperCamelCase
General component lifecycle
Initialization (mounting); State/props updates; Destruction (unmounting).
Redux Store
"actions" represent the facts about "what happened" and "reducers" update the state according to those actions. "STORE" is the object that brings them 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).
Redux prescribes that you concentrate your model update logic in a certain layer of your application...
"stores" in Flux, "reducers" in Redux
What is node?
A javascript runtime for network applications like web servers. A JS enigne (V8) and a set of libraries that make it possible to write and execute network applications in Javascript.
error after axios call
.catch(error=>console.log(error))
after axios call chain
.then(response => { console.log(response.data); this.setState((state)=>{ state.wines=response.data; return state;
The Three Principles of Redux are...
1. "Single source of truth" The state of your whole application is stored in an object tree within a single store. 2. "State is read-only" The only way to change the state is to emit an action, an object describing what happened. 3 "Changes are made with pure functions" To specify how the state tree is transformed by actions, you write pure reducers.
In Redux to tie state and actions together, we write a..
A function called a reducer. A Reducer is just a function that takes state and action as arguments, and returns the next state of the app.
what do you put between error and console.log
=>
virtual DOM
A JS object that is a virtual representation of the DOM. Any new view changes are first performed on the virtual DOM, which lives in memory and not on your screen. An efficient algorithm then determines the changes made to the virtual DOM to identify the changes that need to be made to the real DOM. It then determines the most effective way to make these changes and then applies only those changes to the real DOM. This guarantees a minimum update time to the real DOM, providing higher performance and a cleaner user experience all around.
JSX
A dialect of JavaScript that embeds raw HTML templates inside JavaScript code. JSX code by itself cannot be read by the browser; it must be transpiled into traditional JavaScript using tools like Babel and webpack.
Webpack
A static module bundler for modern JavaScript applications. It recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles.
async library
A utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Provides around 70 functions that include the usual 'functional' suspects (map, reduce, filter, each...) as well as some common patterns for asynchronous control flow (parallel, series, waterfall...). All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your asynchronous function -- a callback which expects an Error as its first argument -- and calling the callback once.
ReactDOMServer API
API for server-side rendering initial HTML. renderToString(element) - render initial HTML to string for faster first load, then Hydrate with client JS. renderToNodeStream(element) - same as above, but sends data as stream for faster transfer byte-by-byte
React propTypes
API for typechecking props. Throws warning if an invalid type is provided for a prop
ReactDOM API
API providing top-level methods for DOM manipulation: render(element, containerRef) - Mount/update a react component to DOM hydrate(element, containerRef) - same as render, but for SSR HTML unmountComponentAtNode(containerRef) - remove component from DOM and clean up event listeners and state findDOMNode(component) - returns correspondingnative DOM element (throws exception for unmounted Component) createPortal(child, container) - a way of rendering an element outside of normal the native DOM hierarchy of the component, while preserving React DOM hierarchy. Good for Modals.
In Redux to change something in the state, you need to dispatch an ....
An action , a plain JavaScript object that describes what happened.
Webpack Entry
An entry point indicates which module webpack should use to begin building out its internal dependency graph. After entering the entry point, webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).
context
Context lets components make data available to other components further down the tree without being passed through explictly as props. When a component defines some data onto its context, any of its descendants can access that data. That means any child further down in the component tree can access data from it, without being passed it as a property.
state
Data associated with a component that changes over time. The most important difference between state and props is that props are passed from a parent component, but state is managed by the component itself. A component cannot change its props, but it can change its state.
module
Discrete chunk of functionality. Each module has a smaller surface area than a full program, making verification, debugging, and testing trivial. Well-written modules provide solid abstractions and encapsulation boundaries, so that each module has a coherent design and a clear purpose within the overall application.
socket.io library
Enables real-time bidirectional event-based communication.
React API
Entry point for react library. Component - base class for React components when they are defined using ES6 classes. PureComponent - same as above, but implements shouldComponentUpdate() based on shallow comparison of state/props createReactElement(type, [props], [...children]) - method underlying JSX statements. Children - utilities object for dealing with the this.props.children opaque data structure (map, forEach, only, toArray). Fragment - Component that lets you return multiple elements in a render() method without creating an additional container DOM element createRef() - creates a ref that can be attached to React elements via the ref attribute.
Jest
Facebook's JS testing platform, includes testing snapshots of serialized component Assertions: expect(component) .toBe(value) .toHaveBeenCalled() .toHaveBeenCalledTimes(int) .toHaveBeenCalledWith(arg, arg, arg, ...) .toHaveProperty(key, val)
React 16 new features
Fragments - allows return of more than one top-level element from component. can be array of elements or <React.Fragment /> Error Boundaries and componentDidCatch - Prior to React v16.0, any error in any part of the UI would crash the whole application. Now a component with componentDidCatch method defined acts as boundary that conditionally renders based on error state createPortal(child, container) - a way of rendering an element outside of normal the native DOM hierarchy of the component, while preserving React DOM hierarchy. Good for Modals. stream support in serverside rendering (SSR) Context API - lets components make data available to other components further down the tree without being passed through explicitly as props.
When creating components, you have the choice between two different ways:
Functional components (also referred to as "presentational", "dumb" or "stateless" components const cmp = () => { return <div>some JSX</div> } (using ES6 arrow functions as shown here is recommended but optional) Class-based components (also referred to as "containers", "smart" or "stateful" components) class Cmp extends Component { render () { return <div>some JSX</div> } }
JSX can either be either what? And uses what to distinguish the difference.
HTML-like, or component instances CAPS shows it's an instance of a class
react-redux provider
Makes the Redux store available to the connect() calls in the component hierarchy below. Normally, you can't use connect() without wrapping a parent or ancestor component in <Provider>. If you really need to, you can manually pass store as a prop to every connect()ed component, but its not recommended
Redux Things you should never do inside a reducer:
Mutate its arguments; Perform side effects like API calls and routing transitions; Call non-pure functions, e.g. Date.now() or Math.random().
Stream
Objects that allow reading of data from the source and writing of data to the destination as a continuous process. There are four types of streams: read, write, duplex, transform
Major Benefits of React
Performance: rendering and virtual DOM. Unidirectional flow and functional programming. Developer experience: compile-time debugging, JSX, organization, devtools, community, ecosystem.
PureComponent
PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state.
SPA
Single Page Application. An application that loads a single HTML page and all the necessary assets (such as JavaScript and CSS) required for the application to run. Any interactions with the page or subsequent pages do not require a round trip to the server which means the page is not reloaded.
Stub
Stubs are functions that simulate the behaviors of components/modules (i.e., dependencies). Used to provide expected data/functionality from a component/module that IS NOT being tested
Redux store
The object that holds application state and provides the following methods: .getState() - allows access to state .dispatch(action) - updates state; .subscribe(listener) - registers listeners
where do you put instructions for a component
between the { }
methods are effectual
by returning elements
what is state?
change
Redux runs in what environments?
client, server, and native
what kind of component is this import React, { Component } from 'react'
component with life-cycle
component did mount with axios
componentDidMount(){ axios({ method: 'get', url: 'http://myapi-profstream.herokuapp.com/api/f4b493/wines', responseType: 'json' }).then(response => { console.log(response.data); this.setState((state)=>{ state.wines=response.data; return state; }) }).catch(error=>console.log(error)) }
method used with axios call
componentDidMount(){}
state is only available
from "class" based components extending "Component" not from function based components class App extends Component { state = { example: [ {number: 123}, {number: 456}, {number: 789} ] } }
Update hooks
componentWillReceiveProps - (deprecated) getDerivedStateFromProps shouldComponentUpdate componentWillUpdate - (deprecated) render getSnapshotBeforeUpdate componentDidUpdate
Destruction hooks
componentWillUnmount
react-redux connect
connects a React component to the redux store via mapStateToProps and mapDispatchToProps. Makes component a subscriber to certain parts of store state, as well as sets up component to dispatch actions to store
create div without jsx
const greatestDivEver = React.createElement( "div", null, "i am div" );
write a loop with a key
const people = ['Rowe', 'Prevost', 'Gare']; const peopleLis = people.map((person, i) => <li key={'person_' + i}>{people}</li> <li key={'person_' + i}>{person}</li> ));
Initialization hooks
constructor static getDerivedStateFromProps componentWillMount - (deprecated) render componentDidMount
Steps to setup redux
create store define initial state define reducer(s) (combine reducers) define actions wrap app in provider map state to props map dispatch to props
flow in react
data flows downward. behavior flows upward
How do we change something?
event
concurrency
executing multiple function calls simultaneously, out of order, or partially. Can be achieved through multithreading or async
what do you put at the end of app.js?
export default App
you always name class same as what
file