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.
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 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

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 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. 

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{
        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.

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

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 ().




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. 


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

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

coveres teseting
index.css --> css for the index.html

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

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. 

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(() => {
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

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

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]

#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. Firebase auth not yet supported

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


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. 

No comments:

Post a Comment

React UI, UI UX, Reactstrap React Bootstrap

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