Ad

Saturday, May 30, 2020

React + React Native Basics in 2021-2022

A basic react app import, styling, component and render

I am writing new blog posts for technologies every year because they change, they evolve. JavaScript today is nothing like the JavaScript 10 years ago. Today's topic is React and React Native. This is a narrative style cheat sheet of React Basics. It is my hope to organize those concepts in a cohesive way. It will tell you how the concepts are connected, but to find out more, to dive deeper, it is important to seek out external tutorials and resources. 

React is the declarative way to create web components, as opposed to vanilla javascript uses imperative, step by step, line by line instructional programming. ReactDOM inserts React components and render them onto a web page. Babel translates JSX to JavaScript and HTML that the browser can understand. 

Vanilla JavaScript is imperative. React is declarative. Just say you want a behavior / element, it will be there. No need to tell the computer step by step what to do. If the data (state) changes, the view will change to reflect that. It's like having smart elements that just know what to do. 

Repeated elements (groups of HTML tags) are great candidates to break up and to be rewritten as components.

React is a library for building user interface. 

The most important concept in React is components. The functionality, codes are organized into components that become UI elements. Every custom react component uses the extends keyword to inherit from the React.Component class. 

Components are written in tag-like syntax, begins with a left bracket `<` and the name of the component Capitalized. It can be invoked as a function with props as properties. Each component returns a node. Components can also have states,  which are updated with specific setter functions. 


Why JavaScript? It is a great time to learn modern JavaScript (ES6), you can now code both front end and back end (full stack) with JavaScript, even use it for Augmented Reality, Animation, interactivity, games, and machine learning (via Tensorflow.js). 

Post in progress, in construction. Updated daily.

Getting Started
If you want to start with a seed app, try the create-react-app
Provides basic seeding, basic scaffolding
All the javascript files are in the src folder.

Normal to see the node_module folder in all node and react apps. That's where the packages are installed. 

To get a quick start you can use CDN served React using unpackaged instead of npm install

Basic Node commands
Start the node app in command line
$ npm start

install the latest and greatest
npm install npm@latest -g

Launches the placeholder app in localhost:3000

Check versions
node -v
npm -v

Follow React website step to install react.  https://reactjs.org/docs/getting-started.html
Use the following import statement in javascript source code.
import ReactDOM from 'react-dom'
import React, { useRef, useState } from 'react'

Key Concepts in React:

Declarative program : opposite of imperative programming, where we specify step-by-step instruction, implementing behaviors in details. In declarative programming we tell React what we want back, like a component. HTML is a declarative, because we don't need to implement every detail just tell the browser to render a <div>.

JSX : 
JSX stands javascript XML

JSX mix html and javascript together. Write html with javascript. Uses camel case like javascript. 

Most common way to create react element is not use createElement but using JSX
const element = <div className='container'>Hello World</div>
ReactDOM.render(element, rootElement)

React uses JavaScript to write HTML codes using JSX.
const my_html = <h1>Hello World</h1>
It is a combination of JavaScript and HTML, won't validate in vanilla JavaScript. 

JSX philosophy is perhaps for your code to resemble the web components, the declarative nature of html tags,less like pure javascript spaghetti code.

Browser engines don't support JSX and translating JSX to JavaScript that's why we need libraries like Babel to make that translation from JSX to JavaScript. There's a Babel playground where you can see the interpreter in action. Try translating JSX code into Js. 

JSX Allows us to create HTML elements using JavaScript, be able to dynamically evaluate JavaScript statements. Must enclose the entire JSX using enclosing tags <div></div>. Else will have an errorjavascript expressions in JSX will be evaluated 


Components:
Components are great for reusable code in react. Perhaps the most important concept. 

React components, building blocks of the virtual DOM.
Every component needs a render function because it needs to know how to render the component to web page. 
React components auto attach props. When we use it it also knows which props we are referring to. It knows we want to use it

Functional component is good for a simple quick function. It's good/easy for people to get started with react using functional components. is functional component stateless? A functional component is a stateless component. functional components : snapshot, values passed are stateless
// define a functional component in react.  
const App: FC = () =>{ return (…); }

The components codes are organized into the components folder in the src subdirectory. 

Can also nest other components in the window <app /> component
Render(){
<Hello/>
<Hello/>
}


To be frank, a component is a block of reusable code. 

This inside the component refers to the component 

Declarative UI

React core concept

React components rely on data passed to be dynamic

When writing babel code use the script tag <script type="text/babel"></script> instead of the regular javascript tag. 

Functional components describe how UI should look based on states and properties 

When writing JSX, we may also see {} which surrounds JavaScript expressions {my javascript expression}. it cannot interpolate complex JavaScript logic such as control flow. But can handle expressions and ternary operators. JavaScript inside {} will be interpolated. 
{{}} is interpolated as an empty object. 
hyphen? todo

New component tag name needs to be capitalized. When inspect the type of object, the element will not show as a normal HTML tag such as a tag, but a special component, custom component, with custom tag name reusable using custom component. 

When initializing, component calls construct, super if any inheritance and yes generally it will, to enable the component, setState to give initial values to the state.

State management. Track state. 

react.createElement() API is different from the createElement API on document
textText becomes children
just specify the type of element and pass in property value pairs as an object
can also pass in children as an array
react for creating the elements
react dom for rendering elements to the page


Babel 

Babel is the javascript compiler
tryout playground available
compile JSX to vanilla javascript


is used to convert JSX code to JavaScript, which is understood by the browser. We use the script tag with text/babel as type to tell Babel this code needs to be compiled. Babel will insert a new script tag on the page in JavaScript that the browser Js engine can understand. 

Apparently the best practice is not to use Babel stand alone. 

Libraries:
React Core
    React core does not have the request module - one example why we need ReactDOM. 
ReactDOM : insert components into DOM. Takes components insert into DOM.
Babel : compatibility, helps convert JSX to JavaScript (Browsers can understand Js code, not JSX)
React Native : Build mobile apps using just JavaScript. Write once, deploy any where. Supports iOS and Android. Dependency is React. JavaScript is bundled, transpiled from ES7 ES6 ESNext down to ES5 code. Also minified (Source: CS50 Harvard). Multiple JavaScript files compiled into a one big JavaScript bundle. Separate threads for UI, layout, JavaScript (which is Single Thread and can get locked up). Prerequisite of React Native learning is to know core React concepts. Install Xcode for iOS dev. Install android studio for android development. Yarn for package management, installing additional libraries modules. Have React native documentation ready.

Link to React, ReactDOM, and Babel using script tags in the headers.

Basic unit of react organized around components. It inherits from React.component. Usually contains a render function. 

class CappedComponentName extends React.component{
    render(){
        return <h1>Some HTML Code</h1>
    }
}

Props : objects that are passed to elements. It looks similar to JSON, but unlike JSON which can only handle strings, props can handle other JavaScript data types. 
React uses setState to change state props.

When modifying state in react, it is important to use the corresponding state setter, for example useState. If we don’t return a copy of the state and modify the state (using the setter), if we modify the state directly, it won’t be picked up by React’s differentiating algorithm, and wouldn’t recognize the change and update components properly. 

Quiz:  what's the difference between state and props. 
Private versus public

Arrow function: 
Benefit of using arrow function, is to handle the event variable and bind this correctly. this object can get kind of funky in js. 

Best practice:

A workaround best practice to ensure compatibility is to compile JSX to JavaScript before deployment. 

What is the different between props and states. States is something the component may want to track and modify. Props is somewhat like initialization, configuration, like states but with fewer changes

Use case:
    React can convert JSON data quickly to HTML
    React is really good for repetitive HTML, generating a lot of HTML templates repetitively which vary with data
    React components make coding easy
    React helps developer handles States
    React helps HTML page display data
    
Performance : 
DOM : takes html document, creates a tree like structure. React virtual dom : copies the tree into a memory, whenever something changes,
react will find what's different, doing an in-memory comparison to the tree update only what's needed. Instead of refreshing the entire screen (less efficient).

    Virtual DOM means fast screen update. Especially when there are quite a few controls, components on the screen. 
    Virtual DOM computing and re-rendering with delta change only makes React performant, less expensive DOM rendering, refreshing, layout change with data.
    Virtual DOM manages delta update by monitoring changes and understand what constitutes a re-render, re-render partially, instead of regenerating DOM from scratch, which is costly and expensive

In general, front end development frameworks help reduce DOM manipulation work, and improves code quality 


Post in progress, in construction. Updated daily.

Components:
React components are independent, easy to maintain, reusable. Describe how components should look based on states, properties. state can be think of as a configuration


State:
In constructor we define the state of the component, what does the component needs to keep track of
this.state = {} property value pairs. state can be think of as a configuration

State is dynamic
State contains data that can change. In contrast with props. 

State is used on a class component not a functional component.  class based components are more like objects, have states, lifecycle hooks. lifecycle means they are kind of alive. And there are lifecycle events.

Initial state vs changes of state

Functional components in React are Stateless. For Stateful components, use class components.

Styling React  | Make React App Pretty
Use React UI, Material UI
React UI includes cards, breadcrumbs, tree, accordian, 

Render function
Related concept : Virtual DOM
React Render function takes 2 arguments : element, target

For the return function to span multiple lines in render use ().
render(){

    return(
        <h1>

        </h1>
    )

}

We still need to call ReactDOM.render() and give it the location and component to render in order to display the UI on the page. 

-----

If data changes, in an eligible event, can trigger changes to all the components that use the data. 

----
React modules
import React from 'react'
that's the core react module. There is also a react module for react web (react-dom) and react native (mobile). Used to be one big app. 
Even have a module for VR. 
----

Files

App.js 
main top level component, 
a wrapper for the rest of the project. Point to other component code. 

App.css 
main css file, 
Can organize css for other components, 
one css file per component. 

App.test.js 
coveres teseting
index.css --> css for the index.html

.gitignore
is good for ignoring sensitive information, large uneccessary files such as node_modules, etc.  such as data files. 

package.json
not specific to react
 common in all node projects
 contain information about the app, such as author dependencies, such as react-dom, react-scripts (used by create-react-app)
package.json the file that describes the node project
also describes dependencies

npm install command will install these dependencies

---
Best practice: 

When removing a .js or .css file be sure to also remove any related import statements.

Divide a web app into logical components to organize, render and update with data. 

serviceworker for push notifications.
--
React modules
react core is used for creating elements
react dom is used for rendering the elements to the DOM

----
React createElement method creates an element using React instead of using the vanilla javascript. This element can used and manipulated using react easily.

Make your React app look pretty using React Bootstrap as a starter. Animate your app using React Spring. 
----
React Fragment
Can render elements side by side which is other wise not possible
Great for rendering tables which has a lot of tags side by side

short hand <></> is the functional equivalent of fragments in JSX. Fragments enables rendering two adjacent JSX components at the same time. 

React Dev console
React UI Kit for rapid prototyping. React bootstrap. 

UseEffect
Previously have to be done using class, use this keyword. useEffect, component lifecycle, lifecycle events are also called side effects

UseEffect - Component Lifestyle
componentDidMount{...} component is added to the UI, happens once
componentDidUpdate{...} data can change component is updating, updated multiple times
componentWillUnmount{...} destroyed, happens once, component will be removed from the UI
2nd argument to useEffect
array of dependencies
useEffect() hook logic
takes a function you define as first argument 
react will run your function aka side effect after it updated the DOM
useEffect() will run whenever state changes, 
useEffect(() => {
alert('');
})
run the function any time stateful data changes on the component
run once when the component is initialized, with default
run again each time the state, count is updated

Need to be careful of infinite loop:
if our function calls something that that updates the state,
then the function will be called again and agian in an infinite loop

can add second argument to useEffect()

an empty array of dependencies []
will run once when the component is mounted, once

can also add state to the dependency array
so it tracks state variables

useEffect(
() => {
fetch...
can also add a tear-down function here. React will call it when the componet is destroyed
return  () => {alert("goodbye!")}
},
[count]
)

react context api
share data without passing props, shared scope, 

useState is a hook
handle reactive data, 

Any data that changes in the app is called a state

so latest changes are reflected to the end user
destructure with a getter and a setter
const [count, setCount] = useState(0)
default value inside

React Developer Tool

As of 2020, the react developer tool has 1283 plus reviews, and 2mm users in the chrome extension store!

React hook 

Introduced around 2019, a React function. Reusable function.  0 is the default in the hook. 

chakra ui react theme provider
react-final-form form handling

React Hook react component lifecycle [public]
https://ml.learn-to-code.co/skillView.html?skill=Wp37IYN0giyDjmm0F3mZ

#react #js #webdev 

Development server : Use development server to preview the app on local machine using localhost without building constantly. 

Using React Native with firebase

Some options, but none of them ideal. 
https://github.com/invertase/react-native-firebase/tree/master/packages/auth Firebase auth not yet supported
https://github.com/firebase/firebase-js-sdk
https://docs.expo.dev/guides/using-firebase/

Do you have any react native templates that you recommend? Comment below

Gatsby 

is a React-based open source framework for creating websites and apps. Build anything you can imagine with over 2000 plugins 
and performance, scalability, and security built-in by default. Gatsby is for react js As Wordpress is for php?

How to debug React apps
---
Review : Coursera React project, loosely put together, not a polished course, but very effective, the instructor gets to the point, it's efficient

Intermediate React
Data binding

---

Performance : forever animation drains battery / power /energy. 

Sunday, May 10, 2020

Intro to Data Visualization

REPOST from Medium with permission

Data Visualization in Machine Learning — Beyond the Basics

This is not a tutorial. These are my notes from various Machine Learning articles and tutorials. My personal cheatsheet for interviews and reviews. Any feedback and corrections are welcome. If you’d like to read more, please let me know as well. These notes are more applicable for python users. Does not include ggplot, great for R.

Prerequisites and Dependencies

This tutorial and overview is python based so we use matplotlib.pyplot. These commands can be run in command line and in Python Notebook with just a bit of modifications. Any reference to plt means the function is from the matplotlib library.
import matplotlib.pyplot as plt
# will get object does not have bar, scatter.... function_name error # if not imported

Plot a Bar Chart

Bar chart, bin chart: useful for frequency analysis, distributions and counts.
labels = ['A','B','C','D','E','F','G']
nums = [13,24,5,8,7,10,11]
xs = range(len(nums)) #[0, 1, 2, 3, 4, 5, 6]
#xs is a convention variable name for x axis
plt.bar(xs,nums)
plt.ylabel("Customize y label") 
plt.title("Customize graph label")
plt.show() #display the plot


Don’t be deceived by its simple look. Frequency analysis is very powerful in data EDA, stats and machine learning.

Plot a Histogram

Histogram will automatically divide data into bins.
import matplotlib.pyplot as plt
import pandas as pd
nums = [99, 1, 3, 5, 7,33, 23,684, 13, 3 ,0, 4]
pd.Series(nums).hist(bins=30)
# <matplotlib.axes._subplots.AxesSubplot object at 0x10d340d90>
# returns object in memory
plt.show()


Also useful for visualizing distribution and outliers.

Scatter Plot

How is scatter plot beyond the basics? Scatter plot is extremely intuitive yet powerful. Just plot the vertical coordinate and horizontal coordinate of each data point in the sample to get its scatter plot. If the relationship is non-linear, or there may be the presence of an outlier, these targets will be clearly visible in the scatter plot. In the case of many features i.e. dimensions, a scatterplot matrix can be used.
Below is a screenshot of pandas scatterplot matrix in the official documentation.


Clearly the relationship is not linear. The diagonal is the variable vs itself, so it’s showing a distribution graph instead of scatter plot. Neat, looks like the variable is normally distributed.
Scatterplot is a great first visual. Too many features? Try sampling or generating data subsets before visualizing.
Use pandas.DataFrame.describe() to summarize and describe datasets that are simply too big. This function will generate summary stats.
Scatterplots are useful for pairwise comparison of features.
Scatterplots can go beyond two dimensions. We can use marker size and color to illustrate the 3rd dimension, even 4th dimension as in the famous TED talk of economical inequality. The presenter even used timeline (animation) as the 5th dimension.

Visualizing Error

Youtube deep learning star Sraj shows a 3D visual of error function while altering y intercept aka bias and slope for linear regression. The global optima i.e. the global minimum in this case is the goal of gradient descent algorithm.
Error functions have shapes and can be visualized. Local optima which prevents your model from improving can potentially be visualized.


Gradient can be visualize as directional arrows that travel in the direction of the global minima along the shape of the 3D plot. It can also be visualized as a field of arrows in a matrix.
Each residual (y_i — y_hat) can be visualize as a vertical line connecting the data point with the fitted line in linear regression.

Data Scientists Love Box Plots

Why? It displays essential stats about distribution in a concise visual form. Aka candle stick plot. Also popular in finance.
Max, 3rd Quartile, Median, 1st Quartile, min.
This is known as the box and whisker graph too. It’s popular among statisticians. Used to visualize range. It can be drawn horizontally.
What’s between Q3 and Q1? The interquartile range, which used in analyzing outliers. Q1–1.5*IQR is too low, Q3+1.5*IQR is too high.
Box whisker plot displays outliers as a dot!
Check out Boston University’s Blood Pressure dataset box whisker plot with outliers.


Heatmap

Did you say heat map? Heat map has been in and out of favor. Web analytics still use heat map to track events and clicks on a webpage to identify key screen real estates. Why should we use heat map for machine learning?
It turns out that generating a heat map of all the feature variables — feature variables as row headers and column headers, and the variable vs itself on the diagonal— is extremely powerful way to visualize relationships between variables in high dimensional space.
For example, a correlation matrix with heat map coloring. A covariance matrix with heat map coloring. Even a massive confusion matrix with coloring.
Think less about the traditional use of heat map, but more like color is another dimension that can visually summarize the underlining data.
Correlation Matrix Heat Maps are frequently seen on Kaggle, for exploratory data analysis (EDA).


More Data Visualization Magic

Did you know that you can visualize decision trees using graphviz. It may output a very large PNG file. Remember the split of decision tree is not always stable — consistent over time. Take it with a grain of salt. The benefit of visualizing a decision tree is to understand where and how machines made decision splits. Decision tree boundaries can be visualized too, see screenshot below from Sklearn documentation.


Visualizing models, decision boundaries and prediction results may give hints whether the model is indeed a good fit or it is a poor fit for the data. For example, it is high bias to ignore the nature of our data if use a straight line to fit a circular scatter of dots.
Researchers even visualized different optimizers to see their descend to minimize loss.
Did you know you can create interactive plots using Plotly right in Jupyter Notebook? Interactive plots allow you to visualize complex data, toggle and change parameters. For example you can slide to change values of your hyperparameters and visualize how the model performance change in gridsearch and other systematic search of the space.

React UI, UI UX, Reactstrap React Bootstrap

React UI MATERIAL  Install yarn add @material-ui/icons Reactstrap FORMS. Controlled Forms. Uncontrolled Forms.  Columns, grid