React Flashcards
What is React?
Hint: Developed by Facebook in 2011
A javascript library for building fast and interactive user interfaces
React is a library NOT a framework
currently the most popular JS library for building UI
domimating frameworks for building UI (over angular and vue)
developed at Facebook in 2011
Expand job opportunities, know react!
Used by Facebook, Uber, Netflix, Twitter, Pintrest, AirBnB
What is every React application?
A tree of components
each component is independent (UI element)
can build components in isolate + combine for UI
UI elements connected together in a tree:
Navbar
Profile
Feed
What is a component?
a piece of the user interface
built indepently, isolated, re-usable
compose to build complex user interfaces
implemented as a Javascript class
Contains:
state (data to display)
render method (JS object maps to DOM)
Don’t work with DOM API in browsers
Each App:
contains root component
additional components are children
React app is a tree of components
What do we no longer have to do when working with React?
only makes sure view is in sync with state
React is a library NOT a framework
No longer to write code to…
query and manipulate DOM
attach event handlers to DOM elements
Why?
React reacts to state changes (virtual DOM) and automatically updates DOM
What is a react element?
A plain javascript object that maps to DOM
not a real DOM object, just plain Javascript object represents DOM element
React keeps a lightweight representation of DOM in memory
when a change occurs, a new react element is generated
React then compares to real DOM and updates
How is JSX compiled?
Hint: React.createElement ( )
we don’t directly use React from ‘react’ in JSX but…
When JSX code is compiled React.createElement ( ) is called
output of JSX expression is a React element
Ex. type: h1, etc. part of virtual DOM
What is the difference between React and Angular?
React is only a library that helps maintain the view in synch with DOM
Angular is a framework (complete solution)
React has small API to learn
calling HTTP services, routing requires 3rd party libraries (Express)
What are two helpful extensions?
Hint: Simple React Snippets, Prettier
Prettier - helps fomat our code
React Snippets -
What does the create-react-app command do for us?
all config is done for you!
Set’s up React Project:
lightweight server - allows us to host our react app during production
webpack - bundle code together into small packages to optimize load time
babel - compiler lets us write modern Javascript code that works in older browsersoverride settings/customize?
npm run eject
What is jsx?
Hint: Javascipt XML
syntax to describe what UI will look like
compiler (bable) takes jsx converts to vanilla JS (browser can understand)
in components use jsx and leave it to bable to call react
Ex. Babeljs.io - takes jsx converts to regular Javascript
What does npx eject do to our app?
allows us to customize configuration
hidden complexities (Bable, webpack, etc) removed
package.json adds dependencies
can add our own webpack, etc.
npm run eject
WARNING
Don’t do this unless you’re an advanced developer
What is Mosh going to teach us about Full Stack architecture in this course?
He is going to show us how to talk to a Node/Express server
focus on frontend
node server running on different port
React app talk to (get / send) data + store in MongoDb
connect to a real Node/Express backend (get/store data in MongoDb)
code given is code created in Node course
What will we learn in this course?
Build a real world video rental application
Feel confident building other applications on your own!
Topics:
Javascript - basics (take his other courses)
Components - building blocks of React
Tables - pagination, searching, sorting (common in apps)
Forms - validation (common in apps)
Routing - taking user between pages
HTTP Services - how to talk to backend services (data in MongoDB)
Auth - services from node backend (Node vs. Firebase)
Deployment -
- *What** is Redux?
- *Hint:** used in 50% of React Project
Used in more than half of React projects
Not every React project needs Redux
Focus on learning React FIRST
learn Redux NEXT
What are pre-requisites of learning React?
Hint: 3 months of Javascript programming
JS basics - teach how to think like programmer, solve programming problems
JS OOP - advanced topics
Basics:
Let / Const keywords
Objects
this
Arrow functions
Destructuring
Spread Operator
Classes
Modules
What is the problem with this code?
Hint: var keyword
variable shouldn’t be accessible outside of a function (scope)
loop variable is accessible outside for loop!
var keyword accessible inside fn defined
Solution?
ES6 declaring variables
Let - only accessible inside block
const - only accessible inside block (constants_
What is the difference between let and const?
Hint: scope limited to block, read only
const - cannot be redefined (read only)
not a variable, cannot be re-assigned
let - variable that can be defined
Use const vs let
use let only when you need to re-assign a variable
What should we know about objects?
accessing properties or methods:
dynamically - bracket notation
static - dot notation
How is the .this keyword diferent in Javascript than Java/C#?
doesn’t always reference current object
value of .this is determined by how a fn is called
if call a fn as a method in an object.this refers to that object
if call a fn as a standalone obj or outside a fn .this returns window obj (global obj)
in Java (.this) always references current obj
How do we bind .this to always reference the current object?
.bind( ) method
takes an arg (obj) that sets .this to point
value of this based on arg passed to .bind
What should we know about arrow functions?
fat arrow between params and body of fn
How does .this behave with arrow functions vs. anonymous functions?
arrow functions bind .this to current object
annonymous functions .this points to globl obj
What did ES6 introduce as a new method in Arrays?
Hint: very useful in rendering lists in React
Map method of Arrays
Very useful for rendering lists in React
callback function transforms each element in array
takes one item at a time, returns a new item
returns a new array
Ex. ${} argument placeholder -> whatever put inside is dynamically rendered at run time
What is object destructuring?
Modern JS feature seen in a LOT React apps
Need to extract value of properties and store in separate variables
What is the spread operator?
Hint: Used a lot in React apps
get every item from an array and spread into a second array
get each individual item in array
can easily clone an array
can apply spread operator to objects
What’s the problem with this code?
To create another object
Have to duplicate code
if future changes, have multiple places to update
Soln?
Classes (template)
constructor takes parameters
.this refers to current obj
new operator is required
How do we use inheritance in ES6?
in React we extend the base class
Why?
Many members are required in our components (re-usable)
How do we import a module in ES6?
What are named exports?
Hint: Named items exported from a module
We can export one or more objects from a given module
When what is exported has a name, called named export
Ex. Teacher module has
Teacher class & promote ()
can export class or function
What are default objects?
If exporting only a single object (single class)
Don’t need curly braces
add default keyword export syntax
Ex. Exporting the Teacher class in a module
A class is technically an object in Javascript
Can have default export + named exports
Default -> import … from ‘’ ;
Named -> import { … } from ‘’;
Can we import both the default export and a named export?
Yes
Very common in React
99% of time call { component } vs. other named exports in React module
What are we going to build while learning components?
Pattern behind items in a shopping cart
Render content dynamically
Apply CSS dynamically
reset quantity of items
How do we load bootstrap in our React app?
npm i bootstrap
import“bootstrap/dist/css/bootstrap.css”
How do we use Simple React Snippets?
imrc -> creates an import statement
cc -> creates a component class
How do we create our first React component?
How can we optimize this code?
To solve the return ; problem
instead of **using a
we can use React.Fragment from React module**
What is the state member of a component?
an object that includes any data the component needs
How can we embed an expression in our components?
can return jsx expression from function
they’re compiled to JS objects
How can we set a component attribute?
How do we set class attributes?
best to use classes for style attributes (performance, maintainability)
How?
jsx compiled to javascript objects
cannot use reserve keyword Class therefore className is used
badge badge-primary m-2 (bootstrap classes)
btn bnt-secondary btn-sm (bootstrap class)
How do we apply styles to React components?
best to use classes (performance, maintainability)
advanced developer?
want to apply styles to only specific element
What are inline styles?
apply styles to different elements
instead of defining a style externally
can pass a style object inline
How can we render component attribute classes dynamically?
Hint: if state= x, make button yellow, if state=y make button blue
give an element a class attribute dynamically
extract to a separate method to keep code clean
How do we render a list dynamically in React?
.map ( )
takes arg -> maps to jsx -> really just a React element -> compiled to JS object
WARNING
each element in the list should have a unique ID so that react can respond to any changes in the virtual DOM
add key = { id }
How can we render a list conditionally?
Hint: Two ways
Create a helper method
Use the logical && operator
What do React elements have?
Properties based on standard DOM events
Ex. onClick, onKeyPress, onKeyUp, etc.
pass function reference to .onClick ( )
How do we bind event handlers?
create a constructor
call the super ( )
alt solution?
Use an arrow function
How do we update the state of a React component?
.setState() method from React component (async method)
calls render ( ) asynchronously
How do we pass event handler arguments in React?
.onClick ( ) must pass a function reference
- Create a helper method - not ideal
- Pass an inline arrow function - better approach
How do we generate a table markup using shortcut?
Hint: table.table>thead>tr>th*4
zen coding
How do we generate a table body using zen coding?
tbody>tr>td*4
How can we create a React component to render the list of movies?
What does a real world application consist of?
Hint: Tree of Components
React is a tree of components
Compose components together to create a complex UI
Very Important Topics
After you’ll have a deep understanding of React components
Topics you’ll use quite a lot in real world applications
Learn:
How to pass data between components in the tree
Raise and handle events
synchronize componts
Functional components
Lifecycle hooks
How can we optimize this code?
Compose elements together
Using an array of components in the state object
How can we pass data between components?
using special JS object called props in each component
external data is mapped to a React component’s props object
How do we render content inside a React component?
Hint: Pass data from Children to Virtual UI
the props.children field
each react component stores data in a props object
props.children hold subcontent
Ex. Dialogue Box componet with content displayed
What is a very useful tool for debugging react applications?
Extension for Chrome, Firefox
React Developer Tools
What is $r in React Developer Tools?
allows us to work with instance of any Component on page in console
What is $0 in react developer tools?
helps us build and debug react applications
Keep React Developer Tools in your toolbox
allows us to work with elements (like buttons)
What is the difference between props and state in a React component?
props
includes data we give to a component
inputs to a component
some components get all data from props, no state
read only, cannot change input to component inside component
purly input to component, cannot modify input
extract props input and store in state to work with it
state
includes private or local data to component
other components cannot access state data
completely internal, cannot access outside
invisible to other components.
Ex. state obj in counters -> internal to counters
What is a very important rule of thumb in React applications?
The component that owns a piece of the state
should be the one modifying it
Ex. adding/removing a counter from the counters array should be done by counters component vs. counter component
BUT
Delete button is on counter component
SOLN?
Have counter component raise an event, counters component will handle it
pass reference to parent method using props.child to our child component
What is a single source of truth?
React component has local storage (state)
Parent also has local storage
Soln?
Remove the local state from components
Keep a single source of truth
What is a controlled component?
remove local state object
receives data only via props object
raises events when data needs to be change
component is entirely controlled by its parent
What is a “no-no” in React?
updating the state directly
Ex. updating the counters[0].value++ directly
must clone object, use setState ( ) replace object
How can we update the state of a React Component?
Hint: Update state of parent w/ stateless child
DO NOT update state object directly
Clone state object, modify
set state to this new object
How can we create a tree of components?
- Make App our root component in Index.js ReactDom.render ()
- Create a hierachy in our App.js file w/ NavBar and Counter Components
- Wrap in React.Fragment when returning multiple components from App
How can we build our UI look / feel?
Bootstrap!
Grab nav bars, lists, etc.
How can share data / keep two components in sync when there is no parent-child relationship (props)?
Hint: How can we display # counters in Navbar w/o a props object?
Lift the state up
Make all elements share same parent (App)
Give access to all children (via props)
Ex. Move state of counters to App component vs. Counter
How do we lift up the state?
Hint: Move state from child components to Root App?
- move state and all methods that modify state to parent (App component)
2. in App component - handle events raised by components (onDelete, onReset, onIncrement) w/ handleDelete, handleReset, handleIncremement
What is a stateless functional component?
Component isn’t storing state
Component doesn’t have event handlers
All data / event handlers done in a parent class
convert component into a stateless functional component
How?
Use a fn that returns a React element vs. a class with a render ( ) method
sfc -> shortcut for a functional component
What are the various lifecycle phases our components go through?
Lifecycle hooks
Special methods we can add to our components (classes)
React will automatically call these methods
allow us to hook into certain moments of a component lifecycle
90% of time, will use listed methods
cannot use in stateless functional components
Ex. Call AJAX after componentDidUpdate ( )
MOUNT
An instance of component is created and inserted into DOM
constructor ( ) - called once during instantiation, set state directly (initialization) based on props
render ( ) - returns a react element that represents the virtual DOM, react then renders it in actual DOM
componentDidMount ( ) - called after component rendered in DOM, make AJAX calls to get server data (setState( ) )
UPDATE
when state or props of a component is changed, these two methods called in order
render ( ) - setState ( ) calls the render( ) method, component tree is rendered (virtual DOM updated) compares virtual vs. old virtual DOM, updates accordingly
componentDidUpdate ( ) - called after update (new state or props) compare new state or props with old state or props, if change, can call AJAX on server
decide whether to make an AJAX call based on changes in state or props.
UNMOUNT
component removed from DOM
componentWillUnmount ( ) - called before component is removed from DOM, can do a cleanup (remove timers/listeners) to avoid memory leaks
What are the MOUNT lifecycle hooks?
constructor ( )
initialize state via props
render ( )
put componet in DOM
all children rendered recursively in virtual DOM (new copy)
componentDidMount ( )
AJAX calls to server
What are the UPDATE lifecycle hooks?
UPDATE
state of component changed or new props given
componentDidUpdate ( ) - new state or props
*if changed, make another AJAX call to update date (optimization technique)
What is the UNMOUNT lifecycle phase?
componentWillUnmount ( )
called just before component is removed from DOM
allows us to do cleanup
Ex. remove listeners or timers (reduce memory leaks)
entire component tree is re-rendered (new copy of virtual DOM)
What happens when the render ( ) method is called during an UPDATE lifecycle hook?
When state is updated using setState ( )
a call to the render( ) method happens
STEPS:
entire component tree is rendered
a new copy of the virtual DOM is created
React compares new virtual DOM to old virtual DOM
updates changed components accordingly (not others)
How do we add the decrement button?
How do we raise and handle events?
Conceptually:
Counters component is raising an event onDecrement
App component is handling event using handleDecrement
Implementation:
using props to pass function references
What are we going to build?
writing clean code, refactoring:
Pagination
Filtering
Sorting
Mosh’s favorite section!!