React.js

Ace your homework & exams now with Quizwiz!

useRef

-returns a mutable ref object -accesses DOM nodes directly -> IMPERATIVE, SHOULD BE AVOIDED -persists for full lifecycle of component -same obj reference every render -does not update on change, must use a callback function to render changes

components

-reusable piece of UI -accepts inputs (called props) and return React elements -props are read only => all React components must act like Pure functions. Use state to change outputs.

useLayoutEffect

1) render 2) useLayoutEffect 3) browser paint -> components added to DOM 4) useEffect() Use when effect is essential to browser paint

JSX: Returning an element within map()

<Box> { arr.map( (item, i) => ( <p key={i}>{item}</p> ) } </Box>

React Redirect (react-router-dom)

<Routes> <Redirect from="services" to="about/services" /> </Routes>

Test-driven development (TDD)

A development methodology in which tests for a function are written before the function is written 1) write tests first 2) run tests 3) write minimal code to make the tests pass 4) refactor both code and tests

React Context

A tool provided by the React library that allows for storage of data and allows any child component to access the data without the need for passing props.

PropTypes

Allows you to control the types of certain props passed to the child component. (TYPE CHECKING) * npm install prop-types CmptName.propTypes: { myProperty: PropTypes.any.isRequired, enumVar: PropTypes.oneOf(["apple", "orange"]) }

yarn

Alternative package manager to npm

Babel vs Webpack

Babel is used to compile JS code so it can be run on older JS engines combined with Webpack used to bundle and optimize the code - Webpack often runs Babel as one of its jobs

ReactDOM.hydrate()

Can be used instead of ReactDOM.render() to perform rehydration (statically load JS and then load JS)

impure functions

Changes the environment or mutates input variables to function

React Developer Tools

Chrome extension to debug React apps; -inspect the React component hierarchies -monitor performance

Context consumer/useContext

Consumer is used to access the context and its data from within a component

How to cancel requests? (e.g. A user may cancel an action during a fetch request)

Create a useRef() hook to determine if the component is mounted or unmounted.

Context provider

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.

Express.js vs Next.js

Express: backend web development framework for Node.js. It is intended for the development of web applications and APIs. Next.js is the react framework for production -> tool for building an HTTP server specifically to perform server-side rendering of a React application

fragments

Fragments let you group a list of children without adding extra nodes to the DOM <>{..cmpts}</>

functional programming

Functional programming, as opposed to imperative programming, is a pure functional approach to problem solving. Functional programming is a form of declarative programming. - Supported in JS. - Functions can do the same things as variables (sent as arguments to a function, can be returned, variables) - functional programming is about transforming data from one form to another -> making copies using functions

Injection attacks

Introduce new input to exploit a vulnerability ReactDOM escapes values embedded in JSX before rendering Prevents XSS (cross-site-scripting)

Isomorphic vs universal

Isomorphic: apps can be rendered on different platforms Universal: same code can be run on multiple environments e.g. universal JS, which can run on server/browser

Why use Node.js with React.js?

It is not required to use Node.js with React. React would work client-side with pure JS. Pros are: 1. utilize a build tool like webpack to bundle client-side code into a tidy package to serve to the client (decreases number of requests required for page) 2. Ability to use JSX as this language needs to be compiled & bundled before deploying (using the package, babel) 3. Create HTTP Server with Node.js and integrate with React.js for frontend. Because React.js doesn't render until the Javascript code is executed by the client, clients that don't execute JavaScript do not have access, e.g. Google's web crawler. There is something called server-side rendering for React for this.

Is JS pass-by-value or pass-by-reference?

JS is considered a pass-by-value language, but at the time a variable refers to an object, the value becomes a reference of that object. pass-by-value: value does not get mutated pass-by-reference: object gets mutated

Comparing JS primitives vs objects?

JS primitives are comparable ( "gnar" === "gnar" ) JS objects, arrays, funcs are the same only if the same exact instance. To compare only the content, can use JSON.stringify()

Jest

JavaScript testing framework designed to ensure correctness of any JavaScript codebase - allows access to DOM and can check what is rendered

useCallback

Like useMemo(), except for functions const fn = useCallback(() => {...}, []); Empty dependency array -> memoized callback is created once

function expressions

create functions inside an expression instead of as a function declaration - can be anonymous and/or assigned to a variable. - cannot be invoked before declared; const test = function () {...} test();

Is a function component pure if it contains state?

No, since the output can vary depending on the state

npm

Node Package Manager npm install package.js * where package.js is the list of dependencies npm install [package-name] npm init -y * creates a new default package.js file

What does it mean when React is isomorphic?

React can be rendered on different platforms other than the browser, e.g. server rendering: UI gets rendered on server before reaching the browser (increased performance, security, portability)

Classes (React)

React uses classes for UI components, but now utilizing functions to construct components instead JS uses prototypical inheritance - technique that makes structures feel object oriented

Array.reduce()

Reduce the values of an array to a single value (going left-to-right) const max = [2,5,7].reduce( (max, val) => (val > max ? val : max), 0); OR const total = [2, 5, 7].reduce( (res, val) => res + val, 0); OR const hashObj = [2, 5, 7].reduce( (hash, val) => { hash[val] = {var, var}; return hash; }, {}) HIGHER ORDER FUNCTION

Array.reduceRight()

Reduce the values of an array to a single value (going right-to-left) HIGHER ORDER FUNCTION

ReactDOM.renderToString()

Render a React element to its initial HTML and return HTML string - Use this method to generate HTML on the server and send the markup down on the initial request for faster page loads - Allow search engines to crawl your pages

JSX

Standing for JavaScript XML, it is a syntax extension for ECMAScript that allows you to write HTML/XML like code inside of JavaScript/React files. Babel is used to transform JSX into readable code understood by browsers

React Native

The alternative JS library for building mobile applications

How does React update the DOM?

We never touch the DOM directly; instead, React updates the DOM for us. React uses the (virtual) React DOM (made of React elements) to render elements in browser. Once React compares the React DOM and DOM, it updates those changes only on the real DOM. Changes to the real DOM are sent in batches instead of sending any update for a single change in the state of a component Apps built with React have a single root DOM node

React Memo

Wraps a component and React memoizes the rendered output of the wrapped component and then skips unnecessary renderings; Creates pure components: given same properties -> renders same output

TypeScript

adds static typing with optional type annotations to JavaScript * .tsconfig.json file for setting up TypeScript

let

allows JS to have lexical variable scope: variables declared within a specific scope can only be accessible within that region

async/await

alternative to fetch; modern way to make async requests (cleaner code) async makes a function return a Promise await makes a function wait for a Promise

fetch

asynchronous request to retrieve data fetch("/api", {method: "GET", body: JSON.stringify({...})}) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); .finally(() => ...); * returns pending promise, which can chained .then() to retrieve data when fetch is successful OR const response = await fetch("/api", {method: 'GET'}); if (!response.ok) { throw new Error('Network response was not ok'); }

create-react-app

autogenerates a React project - skips manual config of webpack, Babel, ... npm install -g create-react-app create-react-app project-name

Node.js

back-end JavaScript runtime environment that runs on the V8 JavaScript engine and executes JavaScript code outside a web browser

function declaration

can be invoked before declared; Hoisting: ability of a function to be invoked at the top of the script before it is declared. Since the function is hoisted at the top of the block but not initialized, it cannot be used until it has been declared. test(); function test() {...}

Rehydration

client-side JavaScript converts a static HTML web page, delivered through server-side rendering, into a dynamic web page by attaching event handlers to the HTML elements

ESLint

code analysis tool that checks your JavaScript code for common problems, such as syntax errors, formatting issues, code style violations, and potential bugs * comes installed with create-react-app npm install eslint

destructuring arrays

const [first] = [1, 2, 3]; const [, , third] = [1, 2, 3]; * list matching

React.js

declarative JavaScript library for building user interfaces. Can compose UIs from small isolated pieces of code called components.

isomorphic-fetch

enable you to use fetch in your Node code in a cross-browser compliant fashion & works for both NodeJs (backend/server) and within the browser

React Router

enables single page apps that allow navigating without refreshing the page and also keeping browser history while preserving the right application view

higher order functions

functions that can accept other functions as arguments and return functions as values const func = logger => message => {logger(message);} const test = func(message => console.log(message)); test("Hello")

Client-Side Rendering (CSR)

generating the HTML components on the browser side, by executing Javascript code within the browser that manipulates the HTML DOM to build the HTML nodes

useEffect

hook for side effects - to perform an action after render - has the same effect as ComponentDidMount - dependency array to associate useEffect to trigger on specific variables - empty dependency array means effect invoked once for initial render userEffect()=>{ ChatAPI.Subscribe(chatName)- effect function return()=>{ ChatAPI.Unsubscribe(chatName) *cleanup function }} * cleanup function - gets invoked when cmpt is removed from tree

In functional programming, is data mutable or immutable?

immutable; the values should never be mutated, instead, we make copies to mutate the value In JS, function args are references to the actual data, so mutating the args changes the actual data.

spread operator

let parts = ['shoulders', 'knees']; let lyrics = ['head', ...parts, 'and', 'toes'] *using spread does not mutate the original object OR can use to retrieve remaining items const [first, ...others] = lyrics;

Hooks

library for adding and sharing state across React's functional components - should only be called at the top level of React function - hooks are invoked in order

Suspense

library for optimizing asynchronous loading in React; when async data for a component is still being fetched, React suspends the component from rendering until data is fetched and provides a fallback UI during the fetch duration

webpack

module bundler: A bundle is a JavaScript file that incorporates assets (JS, CSS, JSX, CSS, HTML...) that belong together and should be served to the client in a response to a single file request. PROS - code modularity - network performance: loads only one dependency, the bundle, in browser Webpack roams over your application source code, looking for import statements, building a dependency graph, and emitting one (or more) bundles. With plugin "loaders" Webpack can preprocess and minify different non-JavaScript files such as TypeScript, SASS, and LESS files. We determine what Webpack does and how it does it with a JavaScript configuration file, webpack.config.js.

pure functions

output depends ONLY on input, do nothing else except return a value (no side effects - does not change their environment) In React, UI is expressed with pure functions

What are the HTTP requests and promise states?

pending, success, fail

imperative programming

programming style that is concerned with HOW we achieve results by code e.g. for(...) {step by step code to do something..}

declarative programming

programming style where apps are structured to prioritize describing WHAT should happen e.g. string.replace(",")

object literal enhancement

pull global variables into objects const name = 1; const name2 = 2; const final = {name, name2};

ReactDOM.render()

renders a React component to a DOM node ReactDOM.render(cmpt, document.getElementById("root"))'

useMemo

returns a memoized value; In a memoized func, result of function call is cached. - if func is called again with same inputs, cached value is returned

Modules (ES6 vs CommonJS)

reusable code that can be incorporated into other files w/o causing variable collisions ES6 - the standard for JS (also supported in Node.js). Keywords are import/export CommonJS - the default for Node.js. Keywords are require ES6 modules are loaded async, while CommonJS are loaded sync

Prerendering

runs client-side Javascript at build time and capturing initial state as static HTML

Server Side Rendering (SSR)

site's content is rendered on the web server rather than the browse; server prepares an HTML file with user-specific data and sends it to the user's machine

synchronous vs asynchronous Javascript

synchronous: instructions executed immediately in order asynchronous: instructions don't block main thread (tasks can run simultaneously)

arrow functions

syntax: let func = (arg1, arg2, ...argN) => { line1; line2; }; returning an obj: let func = (args...) => ({...});

useReducer

takes a reducer function that takes in a current state and returns a new state const [checked, toggle] = useReducer(checked => !checked, false);

Babel

toolchain used to convert ECMAScript 2015+ code into backwards-compatible JavaScript code that can be run by older JavaScript engines. It allows web developers to take advantage of the newest features of the language


Related study sets

Iowa laws, rules, and regulations

View Set

Nutrition for Childbearing; McKinney

View Set

Pharmacology II NR406B Exam 1 (Endocrine, Genitourinary, Acne) Regis University 2015

View Set

Individual Health Insurance Policy General Provision

View Set

Medical-surgical: gastrointestinal

View Set