React UI Library

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is state? What happens when state changes? What is the purpose of state?

A JavaScript object built into React that contains data about the component. When the state of a component changes, it and it's children re-render unless directed not to. The purpose of state is to make the component interactive/dynamic

What is a wrapper/card/container/shell component?

A component that is used in multiple places with various other components placed between its opening and closing tags. They use props.children to refer to all the content that may be placed between there opening and closing tags.

What is children in react?

A prop assigned to all components by default. props.children symbolizes all of the content may come between the component's opening and closing tags for any given use-case.

What is flux?

A state management architecture that was originally popularized by redux.

What can we use as a substitute for if statements in JSX?

A ternary operator. ?

What is a state machine? What is a popular library used to work with state machines?

An explicit model of your state overtime. Xstate.

What does the built in React component "style" prop expect as a value?

An object where each property's key is the css property name, and it's value is the value that you'd like to associate with the css property. Ex: <div style={{height: variableThatDeterminesHeight}} Side Note - The first set of curly braces is to specify that the output will be dynamic. The second set is to specify it's an object.

What is a common file structure for the source folder in a React app? And what is the gist of these files/folders?

App.js (root component) index.js - where you write the logic to hook into he index.html file and render the App component index.css - core generalized styling components folder with all its sub folders, js files and associated css files (component specific and cards/wrappers)

What are two ways we can scope CSS files to specific react components rather than having them scoped globally by default?

CSS modules - fileName.module.css Or Styled Components package can be used in at least two ways You may create the styled component in it's own file and import where desired or you may create a styled component in a file alongside another component if you think that's is the only component that will use the styled component. Both approaches use the Styled Components package. Both require install -> import -> tag template literal

Note video 36

Components can be used just like regular HTML elements with the exception od accessing built-in props such as className{}. The JSX portion of a component is proceeded by the keyword "return". The regular JS portion of the component proceeds the JSX portion and may be incorporated in the JSX portion to make it dynamic by placing the variable/property/prop name between (or as an attribute/prop) the HTML-like tags and curly braces. If you try to add an object between the curly braces it will break the app unless you convert it to a string or are passing it as a prop.

Note Video 39

Components should be kept brief and easy to read. When a component looks like it's becoming too complicated separate it into different components. A component that is nested within another component needs to be passed the desired attributes from its parent component. If a component element does not contain anything between the opening and closing tags, you can remove the closing tag and modify the opening tag to be a self-closing tag. Example of the date attribute being passed to the ExpenseDate component from the ExpenseItem component using a self-closing tag and using the result of what the ExpenseDate component does with the date, in the ExpenseItem component. (parent sends raw material to be modified and then receives the finished product): <ExpenseDate date={props.date} />

What is an alternative syntax for writing a ternary expression in JavaScript?

Condition && what to do if its true. JSX Ex: {filteredExpenses.length > 0 && filteredExpense.map(expense => (blablabla))}

What is the syntax for a ternary expression in JavaScript?

Condition ? what to do if it's true : what to do if it's false Ex in JSX: {filteredExpense.length === 0 ? (<p>No expenses found.</p>) : (filteredExpenses.map(expense) => (blablabla))}

How can data be passed from child to parent in React?

From the parent file, within the custom component tag of the child, create an attribute that points at a function which specifies what you would like to do with the data that you receive from the child. From the child's file pass props into the component function, and use the previously mentioned attribute to pass in the data that you would like to share with the parent. In short, the attribute passed from the parent to the child points at a function in the parent file so that the attribute can be used in the child file to pass data to the function found in the parent file.

What might you do to find the cause of an error?

Google or ChatGPT. Alternatively use the built in debugger tools in the browser. Or a browser extension such as React dev Tools

What is one way to output a list of data dynamically and have it update when a new item is added with React?

In short, filter, map, and state, can be used with an array. We could trigger a state change when a new item is added to an array of objects and the state would be used to trigger the .map method on an array of objects to have it return a list of components that use the individual elements (objects) of the array to determine their display. We could use the filter method to determine which of the array elements to display based on element object properties. And we would have another state to trigger the same operations whent eh filter was changed

Video 57 Notes

In this video we added the "onSubmit" event handler to the form opening tag and pointed it at the submitHandler function that we created to combine the form inputs into a new object for later use. Side Note - the onSubmit event handler will be triggered when the button with type='submit' is clicked.

Video 58 Notes

In this video we implemented two way binding. So we use the input to set the state values, we use the state values to create a new object, we then reset these state values to be empty strings, we then feed those empty string states back into the input in preparation for the next form submission. We do this by creating a new object in the submitHandler that contains the current instance value and then resetting those values to empty strings using the setFuncs associated with them. We also add the 'value' attribute to the input tags and set them equal to their current state. Ex: const submitHandler = (event) => { event.preventDefault(); const expenseData = { title: enteredTitle, amount: enteredAmount, date: new Date(enteredDate) }; console.log(expenseData); setEnteredTitle(''); setEnteredAmount(''); setEnteredDate(''); }; <input type='text' value={enteredTitle} onChange{titleChangeHandler}> Side Note - event.preventDefault keeps you on the same page when the for is submitted rather than redirecting you to wherever the data goes.

What to know about redux

It is a state management library. It is popular on the job market but less so on social media/ with developers.

Is it more common practice to have a react component containing several separate state slices or one state with each would be state slice lumped into it? Why might this be?

It is more common to have separate slices. I imagine this is because it is simpler to write, easier to read, and only re renders each individual piece rather than the entire thing when a change is made so efficiency is increased.

Video 40 - What are the purposes of lines 3 and 4? import './Card.css'; function Card(props) { Line 3 - const classes = 'card ' + props.className; Line 4 - return <div className={classes}>{props.children}</div> } export default Card;

Line 3 sets the default css styles of the card component to the 'card' class from our card.css file and possibly adds a second class as well. The second class can be specified in its opening tag, using ''className" as a prop when it is used in another file. Line 4 is the JSX portion of the 'Card' component that we're creating. Using props.children is what makes this component a wrapper/container

What is an alternative to having separate states within a single component?

Lumping the would be separate states into a single state object that is updated all at once. Or maybe useReduce or Complex but I haven't learned those yet so we'll see.

What is lifting up the state? What should we keep in mind when lifting state?

Passing a state up to a parent in order to be utilized by that parent or passed from that parent to another child for utilization. We only want to lift the state as high as is necessary. Meaning the first shared ancestor between the component that is sharing data and the component that is receiving data. In some cases it may be better to use stuff like - React.createContext, useContext, ContextObjName.Provider ContextObjName.Consumer, useImperativeHandle, or maybe a library like Redux

What are components in React and why are they useful?

Re-usable building blocks made of HTML, CSS, and JavaScript. Components reduce duplication, compartmentalize concerns, and optimize performance. Sidenote - components are not unique to react. React just provides a convenient way to implement this concept on the user interface.

Note Video 33

React has a root component placed in the top level of the src folder. React has separate files for every other component that we create, typically found in a components folder within the src folder. The component tree is the structure wherein the root component is the only one that is actually rendered into the HTML document and all other components are imported into the root component (directly or indirectly). This makes it a SPA. It is common practice to name the component files the same thing that the function/components that are named within the file. Each word in a component name is capitalized. Components are just JavaScript functions that contain JSX.

What are some core differences between Angular Vue and React?

React is primarily focused on visuals of the page. Angular has lots of additional functionality such as routing and uses TypeScript. View is like an in-between. It includes routing functionality. React is currently the most popular of the three. Angular may be preferable for larger projects so that you don't have to include as many third party libraries for functionality.

Why is it improper to lump state slices into a single state using the previously stated method?

React schedules state changes rather than making them instantaneously. The method that we aren't supposed to use runs the possibility of depending on an outdated state. If we use the method on the next slide, react ensures that you use the latest state information.

What are a couple options to avoid passing props manually at each level of the component tree?

React.createContext() or a state management library such as Redux

What does the .getMonth() method do when used on a Date object? What might be a gotcha in relation to this?

Returns the month's numeric value starting at 0 for January. Sidenote general JS not React specific

What is the proper way to combine state slices in a single component to a single state?

Same as card 67 except.. Rather than passing an object that spreads the current state and then updates the desired property into the setFunc(), we pass a function in as the argument like so... setFunc((prevState) => { return { ...prevState, enteredTitle: event.target.value }});

What should we keep in mind about the way that react evaluates code?

Short Explanation - By default it evaluates code only once. Components are only re-evaluated/rendered if directed to do so (change in state). Long Explanation - So if a change occurs due to a component triggering an external function, that change will not be represented in the display of the component, because the component already ran and that's what triggered the execution of the function.

What should be done if you have data that may change, and you would like that change to be reflected on the UI or saved?

Short Explanation: import React, {useSate} from 'react'; const [var4CurrentValue, setFuncName2updatecurrentVar] = useState(defaultValue); setFuncName('Updated!!') Long Explanation - 1) Import the useState function. 2) Use the useState function by passing desired default value (or empty string '' if there isn't one) in as the argument for the function. 3) Set the function equal to an array with two elements. The first element is the pointer associated with the current value in question (name whatever you want) that you'd like to update. The second element can be named whatever you want, but it is common to name it starting with set followed by the original pointer name. The second element automatically creates a function by that name you may then use that function elsewhere in the component to change the value by using it in an event handler function. Ex: const [title, setTitle] = useState(props.title); Side Note - useState is a type of hook.

What does SPA stand for and why is it standard for react ?

Single Page Application. Shifts work from server to client for increased speed. Explanation- With SPAs, clicking on something may look like you're directed to a new page (html file) but in reality, react modified the display of the same html file by using js in the browser. Shifting the processing to the client-side (js running in browser) is faster/smoother than making new server requests for separate html files.

Video 89

Start of new project htmlFor is used in place of for in jsx when connecting a lable to an input.

Section 4 Video 46

State, Event Handlers, Responsive UI

Are the majority of react components stateful or stateless? AKA dumb or smart? AKA presentational or stateful?

Stateless

What is the difference between a stateful and a stateless react component?

Stateless components display data and states that are either static or whose data is received from stateful components. Controlled components are usually stateless. Stateful components have their own source of data.

What is CCS Modules? What does it do to the css styles? How may it be implemented?

Styling library that Creates an object that contains all the css styles you wrote in the .module.css file Assigns a unique hash to these styles for each JS file that imports it so that each use-case is scoped to a specific JS file rather than globally. Sidenote Global scope is default for imported regular .css files. Meaning the styles there-in would be available project-wide after the first import. Can cause unnecessary naming convention confusion. 1 - files should be be named using name.module.css 2 - write styles 3 - in JS file import (typically named styles or classes) from correct file 4 - use className{importName.styleName} on the components that you would like to apply the styles to. If the styleName contains a hyphen than format is classname{importName['style-name']};

What are three common places that error messages may be presented?

Terminal, web page, and console. Compile errors may be found in the terminal and sometimes on the web page. Logical errors may be found in the console.

How might you include conditional logic or a form of looping in JSX?

Ternary expressions and the .map method "if" statements and loops can't be used directly in JSX. Instead write JavaScript code outside of the JSX tags, and then use expressions to include the logic inside the JSX. For example, you can use ternary operators or map functions to conditionally render elements or loop through an array to generate a list of elements, respectively. Exs { condition ? <p>Rendered if true</p> : <p>Rendered if false</p> } {array.map(item => <li key={item.id}>{item.text}</li>)}

What is the following operator called in JavaScript and what does it do? +=

The addition assignment operator sums the left operand and the right operand and assigns the value to the left operand.

What is the purpose of adding a break line to code in source tab?

The browser will stop executing at that line and and return info about it. The info might help you fix the error. If not, you may use the step options to move through the code systematically in source of the problem

What are a few key things that can be found in dev tools under the source tab?

The code as it is seen in the files before it's transformed for the browser. Debugging features such as step, step over, break, step out, step into etc.. Side Note - source tab -> navigate to desired file.

What is the standard file structure of the components folder within a react app?

The components folder often contains children folders to increase organization and make it easier to find things. A component's JS file and CSS file are typically found in the same folder next to one another and have the same name.

Where do we inject our React driven user interface?

The index.html file has an empty Div with an ID of 'root'. The same div that we rendered the App component to as our root.

What is the difference between onChange and onInput?

The onChange event handler is triggered every time a change is made. The onInput event handler is triggered with every keystroke.

What is the type of the input value associated with a change event in React?

The value of an event object is always returned as a string. This is why we sometimes add an empty string as the default value for the setState() associated with change event handlers

When creating a component where should you write the pure JavaScript portion of that component such as creating variables? Once those variables are created how do you incorporate them in the JSX snippet?

The variables should be written at the top of the component function before the JSX/return() portion. You may then use these variables between the JSX tags enclosed in curly braces.

What is typically found within the index.JS file of a react app?

This file imports react-dom/client to use the .createRoot() method. Also imports index.css file and the App.js (or whatever you name the desired root component file) If you use a provider component and want the context to be available app-wide then you'll also import that component file and wrap the App component with it.

Video 63

This section will be on rendering lists AKA arrays dynamically of data and rendering conditional content.

Video 42 Notes

This video shows an intermediate step which react performs under the hood when converting JSX to browser readable HTML. Syntax - Import React from './React'; return React.createElement(desiredHtmlElement, {associated: attributes}, 'content')

Note video 35

To add CSS styling to react components create CSS files within the components folder alongside the components JS files. The CSS files should be named the same thing as the components and component files that they are associated with. We then import the CSS files into their respective JS files. We now have access to the classes and such found within the imported CSS file. Rather than specifying the CSS class within the JSX opening element tag using the keyword 'class', we use the keyword 'className' because 'class' is a reserved word in JavaScript.

What is a controlled component?

Two way binding is used to create a controlled component. Meaning a value that is used in the component is passed on to the parent, the parent does something to it (performs the logic) and it is sent back for display. Thus a controlled component doesn't have internal state. It receives its state via instructions from a parent component. It takes its current value through props and makes changes through callbacks like onClick, onChange, etc..

What happens if you try to add an object between curly braces and the opening and closing tag of a JSX element?

Unless you first convert it to a string then it will break the app. Sidenote Passing an object as a prop within the opening tag doesn't break it

What is composition?

Using components like building blocks.

How may we implement two way binding in react?

We add the value attribute to an input opening JSX tag and set it equal to the current state that the input was originally used to provide data too. We may then write a portion of code where we pass an empty string into the setFunc thus clearing the original input in preparation for a new submission/state. Example on next card.

What is one way we can make the CSS property of a default react component such as <div> dynamic?

We can use a prop called "style" that's built into React's default components to write the CSS inline.

videos 69 and 70 Notes

We created a new folder under components called "Chart". We created components within the chart folder called "Chart" and "ChartBar". In Chart we used the map method to dynamically output the ChartBars because the number of bars may vary. From ChartBars we created a conditional to determine if the the bar has any data points and then to translate the number of data points to a percentage dividing the current bars number of data points by the number of points associated with highest bar. We then use that percentage to make the CSS height property for that specific bar.

What is meant by a declarative approach?

We declare the desired end state/states rather than the specific HTML elements needed to achieve that state. React takes care of most of the direct DOM manipulation under the hood.

What should we keep in mind when updating a state using the previous state as part of the new value?

We should use the function form like so.. const [counter, setCounter] = useState(0); setCounter((prevState) => {prevState + 1}) rather than.. setCounter(counter + 1) Sidenote We do this because state updates are scheduled. Meaning if we used the second example there is a chance that a second state change would be triggered before the first updated state return. In this case but state updates would have essential done the same thing which obviously isn't what we want.

What do we do to keep the JSX portion of the code neat, clean, tidy, short, easy to read?

We write the JavaScript logic above the JSX snippet and use the variables that we create within the JSX.

How does the syntax change when accessing a property from the JSX portion of the component and the JS portion of the component?

When accessing the props from the logic portion rather than the JSX portion we need not use the curly braces.

When is the key prop used? What does the "key" prop do? What is the outcome?

When rendering a list of components it uniquely identifies a component among its siblings. React uses the key prop to determine which items have changed, been added, or been removed. This helps React optimize rendering performance by only updating the components that need to be re-rendered. Using the key prop is especially important when rendering dynamic lists, as it helps React maintain the correct order of elements and prevents unnecessary re-renders.

What must be done if you wish to display two elements on the top level of a react component?

You must wrap them within a separate top level element such as a div, fragment, or <></>. This must be done because react only allows each component to have one top level element.

React Course Overview

components, props, states, react hooks, side effects, refs, context api and redux, custom hooks, routing, deployment, NextJS

What are 4 basic terminal commands that you can run from within the react directory?

npm start - runs the app in development mode. npm run build - Builds the app for production to the 'build' folder. Bundles react in production mode and optimizes build for performance. Runs directly before app deployment. npm test - launches test runner in interactive watch mode. npm run eject - used to modified the default React build tool and configuration settings. It copies the files and dependencies so that we can customize it. advanced stuff

Step 1 - How do you create a new react app?

npx create-react-app appName According to fireship YouTube channel there's a newer better way

How can data be shared from the root component to custom components?

props - From the root component file use the custom component tags and create an attribute in that tag with the desired data. From the custom component file pass in an argument, typically props, to gain access to the attribute.

Note Video 38

props can be accessed in a custom component file outside of the JSX portion of the code without using the curly braces. Ex: const date = props.date; The reason you would write some of the code above the JSX portion is to make it look neater and cleaner. We don't want to write logic in the JSX portion. We'd rather just add the variables.

Note video 37

props explained Ex: From root file - 1) Create JS array of objects. 2) Give access to custom component file like so.. <ExpenseItem DecideOnAttributeName=(arrayName[indexOfDesiredObject].desiredPropertyName)></ExpenseItem> From custom component file - 1) Pass anything into function param. usually 'props' 2) access specific properties inside tags like so.. <h2>{paramName.attributeName}</h2> Full Explanation - Props are used to pass data between components. This enables the re-use of custom components in a dynamic manner. We can set props equal to whatever array, function, obj, etc whose access we want to share with another component. Side Note - You may pass as many props as you'd like. All the attributes assigned to a tag will be grouped together and place in an object by React. That object is not named until passed in as a param in the other file (typically as 'props', short for properties), giving that file access to the associated properties.

What are general concepts to consider when styling?

scope, dynamic vs static

How may we instruct a JSX element to refer to a function for instructions upon some action being taken?

use one of the on attributes as seen bellow <form onSumbit={submitHandler}>

Video 52 Recap

vanilla JS automatically assigns an "event" object to event listeners. React does the same thing on event handlers. To access the event object pass "event" in as the argument/parameter of the event handler function and then inside the function access whatever portion of the event object you'd like. Ex: titleChangeHandler = event => { console.log(event.target.value) } <input type='text' onChange=titleChangeHandler>

Sidenote https://trends.builtwith.com/websitelist/Vercel has a list of companies using vercel along with the LinkedIn profiles of employees there

***

.

.

Explanation of Headless CMS A headless CMS (Content Management System) is a type of CMS that separates the content management and delivery systems. In a traditional CMS, the content management system is tightly integrated with the front-end delivery system. This means that when content is created or updated, it is directly published to the website or application. On the other hand, in a headless CMS, the content management system is decoupled from the presentation layer, which means it provides content via an API (Application Programming Interface) rather than having a pre-defined front-end system. This allows developers to use their own choice of programming languages and frameworks to build the front-end and to consume content from the CMS. In other words, a headless CMS provides a content repository and management system without any pre-built front-end or templates, giving more flexibility to developers in terms of customization and integration with different platforms or channels. This makes it a popular choice for businesses that have a strong focus on multiple channels and delivery platforms, such as mobile applications, IoT devices, digital signage, or even VR/AR experiences.

.

Maybe do videos 282-283 for practice later on.

.

Not finishing section 25 because it complicated, not likely to be useful, and doesn't introduce any new concepts. If I think it might be a good idea to review sometime -- start with vid 349 (summary) and read 396 to make sure that's the functionality I want. 397 has a package the same functionality that I can download rather than writing my own. of course that would introduce another 3rd party library but probably smaller than Redux.

.

Section 25 Replacing Redux with React Hooks

.

Sidenote - Part of a question I asked on video 353 on pre-rendering, server-side rendering, static generation, and getStaticProps But I think pre-rendering is a type of server-side rendering, not vice versa. And isn't pre-rendering just a type of static generation? My research indicates that server-side rendering can be a form of pre-rendering but isn't necessarily. If I understand correctly, pre-rendering is static generation during build whereas server-side rendering can use this approach, or it can dynamically generate data at the time of request. The idea behind server-side rendering is where it occurs, not when. Meaning it occurs on the server rather than in the browser. And in Next 13 (stable) the idea of getStaticProps isn't necessarily to implement pre-rendering but to implement server-side rendering which may or may not be pre-rendered. By default getStaticProps implements pre-rendering but with the use of revalidate it can also dynamically rendered data on the server. Understanding this might be beneficial when thinking about the differences between stuff like using the fallback option along with getStaticProps vs the Suspense component and its fallback prop. Serverside rendering and thus getStaticProps is more about the location than the time. Same goes when thinking about using a loader from React Router vs using revalidate() with getStaticProps from Next.js. In conclusion 1) Pre-rendering refers to the process of generating HTML markup for a website or web application before it is requested by the user, but not necessarily during build time. 2) Static generation is a technique for generating static HTML pages at build time for a website or web application 3) Server-side rendering isn't about when, it's about where. 4) getStaticProps can be used for statically generated html (default) or upon request

.

Sidenote - Web3.js and Ethers.js are a couple of library options that could be used to connect a MERN Dapp to the Ethereum blockchain. In order to interact with smart contracts written in Solidity, the Dapp would need to use the Ethereum network and its associated APIs. The backend (built with Node.js and Express.js) could include an API that communicates with the Ethereum network using Web3.js or Ethers.js to read and write data to smart contracts.

.

Sidenote - should specify that I know ES7 and ES8 in resume other profiles rather than just writing JS. Should specify versions of other technologies as well. React 18, React Router 6.9.0, HTML5, CSS3, Next.js 12 and 13 etc..

.

Skipping section 23 and 24 of course because section 23 hasn't been updated to Next.js 13 (still in Beta) and I don't feel like section 24 (transitions and animations) is a priority at the moment.

.

Start of Section 20

.

.

..

Main overarching Components may be created in a folder called pages rather than the components folder

..

Might be worth spending some time studying the fetch object along with the Response object that's passed to it by default.

..

Pre-rendering and data fetching section

...

React Router Section 20 Conclusion/memory trigger words/key words and associations react-router-dom RouterProvider, createBrowserRouter, Outlet NavLink -> isActive Link -> to, .., relative="path", useNavigate useSubmit createBrowserRouter -> path and index, element, errorElement, children, loader, action, id (for useRouteLoaderData) request & params -> params.paramId, method, url, formData -> get Form -> name="q" useRouteError() - used in errorElement to catch what's thrown from actions, loaders, and renders. isRouteErrorResponse true if what's thrown is a response. !response.ok default JS feature useLoaderData, useRouteLoaderData, useFetcher -> state & Form, useNavigation -> state useActionData - most common use-case for this hook is form validation errors Suspense from React -> fallback Await from react-router - resolve json() utility from react router defer() redirect() Link -> to relative, NavLink, Await -> resolve, Suspense -> fallback, defer -> obj pointing outsource action and loader data, RouterProvider -> router

...

Sidenote - The on events might be worth studying from the react docs Sidenote 2 - When starting a new React job and studying the codebase, it's a good idea to put some emphases on the custom hooks. Maybe, just a personal observation. Sidenote 3 - There are several third party libraries containing commonly used custom hooks Sidenote 3 - There are many form validation libraries

...

Sidenote - windows.confirm() is a function built into the browser and can be used to ask a user if they're sure when they're click something like delete. If you use the Form component to trigger an action windows.confirm will be ignored. The windows object is a major part of the browser environment, kind of like the top level of the DOM. It's a parent obj for the document object which is technically considered the top level of the DOM. So I guess windows isn't a part of the DOM but the overall browser environment. Another Sidenote General Computer Science Stuff We write code using programming languages -> compilers and/or interpreters translate programing languages into machine language (binary) - Computer processor executes the machine code. compilers translate the entire file before triggering execution, whereas interpreters translate and execute each line of code one at a time. Compilers typically generate faster and more efficient code, but the compilation process can take longer. Interpreters are generally faster to start up and can provide more immediate feedback to the programmer, but they may be slower overall and may have more difficulty optimizing code. Interpreters can also be more error-prone, as they do not catch errors until the problematic line of code is executed. In general, compilers are used when performance is a priority, as compiled code can be optimized for the specific hardware it will run on. Interpreters are used when flexibility and ease of use are more important than raw performance, as interpreted code can be modified and run more easily than compiled code. Some commonly used compilers include GCC (GNU Compiler Collection) for C, C++, and Fortran, Clang for C and C++, and the Microsoft Visual C++ Compiler for Windows. Some popular interpreters include Python, JavaScript, and Ruby. It's worth noting that some programming languages can be compiled or interpreted, depending on the specific implementation. For example, the Java programming language is compiled into bytecode, which is then interpreted by the Java Virtual Machine at runtime. This allows for some of the performance benefits of compilation while still retaining some of the flexibility and ease-of-use of interpretation. Running a program involves several processes besides execution and translation. For example, when a program is launched, the operating system loads the program into memory, allocates resources such as CPU time and memory, and sets up an environment for the program to run in. During execution, the program may also interact with other programs or devices, such as input/output operations or network communication.

...

Sidenote windows.alert is a browser function

...

The following is an example of a class-based component creation and utilization of props. import {Component} from 'react'; class ComponentName extends Component = { render () { return ( <li> this.props.blabla </li> ) } } export default ComponentName;

...

maybe look into Object.entries

...

useStates and useReducers along with their default values are saved in memory by react when the component first renders. They are not re-initialized with each state update so the App component being on the top level would have state that is only initialized once because the App component itself is never removed and re-rendered. Some children components may be rendered, removed, and then re-rendered, in which case each subsequent re-rendering of the component would re-initialize their states.

...

Files inside public can be referenced from the ________ of the application similar to _________.

....root of the application similar to pages Ex: <img src="/images/profile.jpg" alt="Your Name" /> //not /public/images/profile.jpg //the above isn't the optimal way to load an image with Next.js. It's the default html way

..blleab

..bla

bla

.blebla

What are 4 redux methods to keep in mind?

.createStore .subscribe .dispatch .getState

When might someone use a dynamic route param rather than a query param?

//Query params are used for passing data between different pages and to the server whereas dynamic params are used to display different instances of the same page (or page illusion in the case of a SPA) based on a particular route/path segment position for a product details page for example. //Query parameters are more commonly used for filtering or sorting data on a single page, whereas dynamic parameters are used to indicate different pages (or illusions of pages in the case of an SPA). //Query params are usually optional and are used to send data to be stored in the database whereas dynamic params of mainly just used to determine what page or page illusion to display. //In general, query parameters in an SPA may be more useful for sending data between components or to the server, while dynamic parameters are more useful for determining which components or pages to render based on the URL.

How is an API route created in Next?

//file location /pages/api/blabla //pass req and res params export default function bleble (req, res) //req.body req.method

How can we create a custom 404 page in a Next.js app? When is it generated? What if we didn't create one? What's a similar page?

/pages/404.js At build time Next creates and statically generates 404 and 500 (server-side error) pages for us at build. We don't have to create customs if we don't want to.

What 3 things must the page file whose path is dynamic contain?

1) React component to render the page 2) getStaticPaths which returns an array of possible values for the path segment 3) getStaticProps which fetches necessary data for particular path segment

What are the steps for creating and statically generating a page with a dynamic path? Maybe revise this answer when I have the full picture

1) create a page using [] in it's name to indicate it's path segment with be dynamic. Ex: [id].js 2) From within that file export an async func called getStaticPaths(){} in which we return a list of possible values for the path segment 3) use getStaticProps to fetch the necessary data by using the `params` prop which contains the dynamic segment pointer/pointers (`id` in this case). //The params prop is automatically passed to getStaticProps and contains all the [] path segment pointers. I think it accessed form the context prop, context.params

Where is the context file created? How is it named?

1) src/store/bla-context.js Side Note - we don't capitalize the name of the folder or file because that would indicate it was a component. Sidenote 2 - you can have multiple contexts files for multiple global states within your react application.

How many mili-seconds is second?

1,000

Explain `expect(outputElement).toBeNull`

3rd A (Assertion). If outputElement (variable we created using `screen.bla`) is null the test will be successful. This is a way to test whether something isn't displayed on the screen (currently rendered in the DOM) when we use a query method on `screen`. //To obtained the `outputElement` we would use a `query` method rather than a `get` method because the `get` methods throw an error rather than returning null if what we're looking for isn't there.

How can we use the current query param value to make the `to` prop of a Link dynamic? For example you might have single form that's both used to sign up a user and sign in a user depending on whether the the current query param value is set to isLoggedIn

<Link to={`?nameOfQueryParam=${isLoggedIn ? signup : loginin}`}> This makes sense because in the URL query params are displayed as the name of the query param set = to is current value.

What react-router-dom component is a special kind of <Link> that knows whether or not it is "active" or "pending"? What is it useful for? What prop does it accept to accomplish this? What does this prop expect as it's value when used in this component?

A <NavLink> is a special kind of <Link> that knows whether or not it is "active" or "pending". This is useful when building a navigation menu, such as a breadcrumb or a set of tabs where you'd like to show which of them is currently selected. It also provides useful context for assistive technology like screen readers. It accepts the className={} prop (the following also applies to the style prop) which works like a normal className, but you can also pass it a function to customize the classNames applied based on the active and pending state of the link. isActive is a Boolean created behind the scenes and by is true if the Link is currently active. Ternary expression to determine CSS style Ex1: <NavLink to="/messages" className={({ isActive, isPending }) => isPending ? "pending" : isActive ? "active" : "" } > Messages </NavLink> Ex2: <NavLink to="/products" className={({isActive}) => (isActive ? classNameA : undefined)}> Products Page </NavLink> Now styles are applied conditionally based on whether the link is active. If the className prop is `undefined` it will have it's default style Sidenote - By default, an active class is added to a <NavLink> component when it is active so you can use CSS to style it. Ex: From js <nav id="sidebar"> <NavLink to="/messages" /> </nav> From CSS #sidebar a.active { color: red; }

What is `fs` in the context of the previous card?

A Node.js module on which we can call various methods to work with dirs and files in the file system

What do we pass between the opening and closing tags of Await? How do we pass the resolved promise from Await to our custom component?

A React Element (JSX element) or a function that will be executed by react router once the promise is resolved (data is there). Can pass it as a prop if using a func. Or if you're just passing element rather than a function between the Await tags -- let React Router pass it automatically behind the scenes and access it with `useAsyncValue()` //useAsyncValue() - Returns the resolved data from the nearest <Await> ancestor component. Ex of passing a function betwen the opening and closing tags bellow.. return <Await resolve={aKeyFromLoaderAKAPromise}> { (BlaToReferenceResolvedPromise) => <customComponentWeMadeOrOtherJSX somePropName={BlaToReferenceResolvedPromis} /> } Ex of just passing an element: From Await file Await resolve={reviewsPromise}> <Reviews /> </Await>; From component file function Reviews() { const resolvedReviews = useAsyncValue(); return <div>{/* ... */}</div>; } //Don't forget that returned dynamic JSX gets wrapped in curly braces as seen above.

Generally speaking what is useSWR? What is it used for? Maybe look further into this in future

A React hook created by the next.JS team. Used for data fetching on the client side. Does a lot including simplifying the process of handling state of remote data. The name "SWR" is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861(opens in a new tab). SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

What does file-based routing mean in Next.js?

A URL is automatically created for page components using their file-path

What is localStorage? What method would we use to store an authentication token here? What should we write alongside the logic to store it?

A browser API. localStorage.setItem('desiredKeyName', nameOfTokenYouWantToStore) In the same action that we write this logic to store the token we should also write a timeout for the token to expire Ex: const expiration = new Date() expiration.setHours(expiration.getHours() + 1) //creates a date that's one hour in the feature. We also want to store this date in local storage localStorage.setItem('expiration', expiration.toISOString()) //.toISOString converts the date to a standard string. Placing something in storage will automatically transform it to a string so we use .toISOString to specify the format of the string to be a common date format and later when we retrieve it we'll easily be able to transform it back to a Date obj.

What is the render() method in React?

A class component's version of a functional component returning JSX. It determines what should be displayed on then UI. Sidenote - the render method also needs to have a return as seen in the previous card. Obviously the logic would be written above the render() method

What is reactJS?

A client side JavaScript library that handles the low level JavaScript to make our jobs easier when developing the UI

What is Vercel? What is it designed for?

A cloud platform as a service (PAAS aka hosting provider) that Next.js apps can be deployed to. Built by Next.js team so it's optimized for it. It's designed for static and hybrid apps built to integrate with headless content. // Some things Vercel does/provides Edge Net Detects when the Next App is deploying and chooses optimal build setting - pages that use static generation and assets will automatically be served from the edge network. Pages that use server-side rendering and API Routes automatically become isolated serverless functions. Provides a deployment URL //DPS refers to Develop, Preview, Ship Develop - Vercel bot will make comments on pull request page Preview - the comment contains a preview URL so you can see the changes that were made Ship - If the branch look good you can choose to merge it to main and Vercel will automatically create a production deployment with build optimization in mind.

What is .Provider?

A component that react creates for context objects by default. Wrapping a component with <ContextName.Provider></ContextName.Provider> gives the component access to the contents of the specified Context Object.

What is the difference between a framework and a library?

A framework has more features and provides more rules that must be followed in regards to how you write your code and perform certain tasks. A framework is less of a specific niche/purpose and more of an overarching structure

What is `matter` in the context of the third to last card?

A function from the grey-matter library that let's you parse the YAML metadata in each markdown file. The matter function returns an object that contains the metadata and content of the Markdown file. The returned object has two properties: data: An object that contains the metadata in the front matter of the Markdown file. content: A string that contains the Markdown content of the file.

What is the purpose of a custom hook? What is a custom hook? What can be done to make them more dynamic from one use-case to the next? What are some things it's commonly used for?

A function used to avoid hook-related code duplication between components. These functions contain other hooks and/or custom hooks. Written just like any other func except name is prepended with "use" just like any other hook. Typically these funcs will accept args to make them dynamic. Often used for fetching data, using complex form state, and WebSockets. Sidenote Separate instances are used for each file the custom hook is used in so that it doesn't mix up the states between components. Meaning the components that use it aren't referencing the same states but rather their specific local states. If we wanted to reference the same states we would use context.

What is a clean up function? Describe and give technical example

A functioned returned within another function such as useEffect whose purpose is to clear the results of another nested function before consecutive re-renders (after unmount/removal from DOM). A cleanup function is a nested function that clears the results of another function before each re-render of the parent function. Bellow example is An arrow function returned within the effect function to clear the previous results of the effect function before running it again. Ex (the return portion of the first argument bellow): useEffect(() => { const identifier = setTimeout(() => { setFormIsValid( enteredEmail.includes("@") && enteredPassword.trim().length > 6 ); }, 500); return () => { clearTimeout("identifier"); }; }, [enteredEmail, enteredPassword]);

What is reactDOM?

A library that comes along with the react library. It is responsible for translating the React stuff to the DOM and comes with its own methods such as .createPortal(). It's like an adapter to connect React to the browser. You need an import entry to use its methods.

What is `shouldComponentUpdate()`? What does it do? When might it be used?

A lifecycle and optimization method used in class-based components who receives props and states whose change wouldn't effect its UI. Used when component and possibly children would otherwise render frequently and slowly without UI change - First consider the use of PureComponent and .memo. Measure performance difference to see if it's worth it. Has potential to introduce little bugs, increases complexity, and stores the prop stores and compares props and states received to do comparisons when ancesters re-renders. Sidenote There are tools that can measure performance and help find performance bottlenecks in the code. II Accepts two args - nextProps and nextState -> compares next with this.state/props to return a Boolean that dictates whether the component should re-render

What is a linter?

A linter is a tool that analyzes code for potential errors, bugs, or stylistic issues. It typically works by parsing the code into an abstract syntax tree, and then analyzing the tree according to a set of predefined rules or guidelines. The purpose of a linter is to catch errors or inconsistencies in code that may not be caught by the compiler or interpreter. Linters can be used for many different programming languages and can be customized to enforce specific coding standards or best practices. They are commonly used as part of a continuous integration/continuous deployment (CI/CD) pipeline to ensure that code meets certain quality standards before it is deployed to production.

What is `path` in the context of the second to last card?

A node.js module that lets you manipulate file paths //I've used this in the full stack course before

What is Next.js?

A production framework for react. AKA Full-stack framework for react. Good for large scale apps. Replaces the need for some other libraries that would typically be added to a React App. //Makes it easier to write the code for splitting the workload between the server and client.

What does fetch return?

A promise/response object because http requests are asynchronous. The promise object allows us to react to the responses of our requests.

What is <Head>

A react component that's built into Next.js and allows you modify the <head> of a page import Head from 'next/head';

What is used to send data from a component to the redux store?

A reducer function Sidenote a reducer function is general programing concept not directly linked to the useReducer hook.

When is it a good idea to use the reducer hook?

A reducer is a good idea to use in a React application when you need to manage state updates that are based on an action and the current state. Reducers are particularly useful when you have complex state updates that depend on multiple state values, or when you need to perform updates that are not easily expressed as a simple assignment to a state value.

What is the following and what does it do? /\.md$/

A regular expression. The forward slashes delimit the pattern, the backslash escapes the dot (.), and the dollar sign anchors the pattern to the end of the string

What is dangerouslySetInnerHTML

A special React prop supported for all built-in components. An object of the form { __html: '<p>some html</p>' } with a raw HTML string inside. Overrides the innerHTML property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn't trusted (for example, if it's based on user data), you risk introducing an XSS vulnerability. Ex: <div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />

What does the index.js file in the pages directory contain?

A standard React component for the homepage (aka root page /)

What does the reducer function receive? What does it return? What can't it contain?

A state and an action. It modifies the state in a predictable way based on the action it receives and returns it. It doesn't contain side effects. The same input always produces the same output. An action is a JavaScript object that uses a type property to indicate the kind of operation the reducer should perform. It may also send some data (a payload) for the reducer to use in its operations.

What is a serverless function?

A type of cloud computing where the cloud provider manages the infrastructure and automatically provisions and scales resources

What is a promise? What are promises returned by?

A value that resolves another value (a pointer to a future value). Promises are returned by async functions.

What could we do to add route protection and avoid the problem described two cards ago?

Add a loader to the route that checks for the auth token and `redirect`s if the token value is undefined. Probably redirect to login page

What are three different times you might indicate the validity of form inputs on the browser side?

After inactive period of typing, on unfocus (onBlur), and on submission (onSubmit).

What are a few places an authentication token may be stored after the server logic creates it and sends it to the client?

After we extract the authentication token from the response we can store it in memory, local storage, or cookies to name a few

How does Redux work?

All state is stored in it. Components access various slices by subscribing to it. Redux notifies them when updates are made to the data/state.

Which of the following is a good use case for an API Route? Saving incoming data to your database Securely communicating with a third-party API Previewing draft content from your CMS All of the above

All the above

Where and when does getStaticProps run by default?

Always runs on the server and never on the client. When depends on the code you wright. By default it runs during build (static pre-rendering aka static site generation aka static generation). Or with the correct specifcations it can implement server-side rendering (at request, dynamic pre-rendering).

What should be used in parent route elements such as a layout component to render their children route elements if using the React Router library?

An <Outlet>. This allows nested UI to show up when child routes are rendered. function RootLayout() { return( <> <MainNavigation/> <Outlet /> </> ) }; Longer explanation App file - const router = createBrowserRouter([ {path: "/", element: <RootLayout/>, children: [ {path: /partOfURLAfterDomainName, element: <ComponentTag />}, {path: "/products", element: <Products/>} ]}]); RootLayout page/file - import {Outlet} from 'react-router-dom'; import MainNavigation from 'blabla'; function RootLayout() { return( <> <MainNavigation/> <Outlet /> </> ) }; export default RootLayout; //In the above -- RootLayout is a custom component that we're using as our layout wrapper. //We indicate the layout wrapper from within createBrowserRouter by adding the children key to its object and passing an array that contains its children routes. //In the RootLayout component we need to specify where its children routes and components should be rendered by using the Outlet component. Now the MainNavigation component and the links in it are displayed at the top of all the children pages, the links will function properly, and the conetnt for the current children page will be rendered in the place of Outlet which in this case is bellow the MainNavigation component. We can have as many layout wrappers as we want to display different links on different pages

What is an AST?

An abstract syntax tree is typically the result of parser reading the source code and generating a tree structure that can be analyzed with tools such as compilers and linters The AST is often used as an intermediate representation of the source code, enabling tools to perform various analyses or transformations on the code, such as optimization or refactoring. ASTs are widely used in the development of programming languages, compilers, and other tools that work with source code. They are also used in various applications such as static analysis, code generation, and refactoring tools.

What are class-based components in react?

An alternative to function-based components that's rarely used in new react development but may be useful to understand when working with old code and creating error boundaries. Class-based components are required for error boundaries. It hasn't been used since React 16.8 introduced hooks. As result Class-based components can't use react hooks.

What is passed into .then()

An arrow function to work with the response object that has a bunch of data about the response. .then(response => { console.log(response.blabla) })

What does the loader prop in createBrowserRouter expect as value?

An async func

What does react automatically assign to event handlers?

An event object that can be used to access details about the event. Sidenote I think it's actually more of a universal JS thing

What is <meta>

An html element used in the <head> (or <Head in the case of Next.js) to provide structured metadata about a homepage and thus increase SEO. Multiple <meta> elements can be used to provide multiple attributes within a single <Head> or <head> section. In HTML 5 there are 4 valid attributes -- content, http-equiv, name, and charset. //The Wiki listed many more attributes after stating this so IDK The significance of meta tags is debatable. They play a role in SEO even if it's only a small part of a much larger picture. Google have stated they update their ranking rules every 48 hours. Under such circumstances, a definitive understanding of the role of meta tags in SEO is unlikely.

What does defer expect as an arg?

An obj containing a prop for each of the http requests associated with the particular page. Ex: defer({ anyKeyNameYouWant: nameOfOutsourceFunction(), etc.. })

What does calling useFetcher() return?

An object

What is the value associated with the `data` property (key) of the object returned from calling matter(blabla)? And in what form -- string number object, etc?

An object containing the data extracted from the YAML front matter in the blabla string

What does the Provider component 'value' prop typically receive as an argument?

An object whose keys are used by the wrapies to access the stuff associated with its values such as states and handlers. Ex: <AuthContext.Provider value={{ isLoggedIn: isLoggedIn, onLogout: logoutHandler, }} In other words - If a component is wrapped in the provider it can use the keys to trigger and access the values in the object by using the useContext() hook

Where are page components located in Next.js?

Any component file contained in the pages directory even if it's nested.

What happens if you return `fallback: false` within getStaticPaths

Any path not rendered by getStaticPaths will result in a 404 page

What are the 3 As in relation to writing a test (anonymous portion of test() func)? What is the general idea behind each A?

Arrange: This involves setting up the initial state and conditions necessary to run the test. This may involve creating objects, setting values, or mocking dependencies. //We used render() from React Testing library to render the component we wanted to test Act: This involves performing the action that is being tested. This may involve calling a function, invoking a method, or simulating a user interaction. //We used jest.mock and jest.fn from jest and userEvent from user-event Assert: This involves verifying the results of the action that was performed in the Act step. This may involve checking values, comparing expected and actual output, or verifying that certain behavior occurred. We used `screen` from react testing library Arrange Ex: render(<ComponentName />) Act Ex: import userEvent from '@testing-library/user-event'; //has methods for all the typical event such as clicking, hovering, double clicking, etc.. Ex: const user = userEvent.setup(); await user.click(screen.getByRole('button')); //userEvent is part of the user-event library which is part of the @testing-library suite. screen i spart of the React Testing Library which is also part of the @testing-library suite or await userEvent.click(screen.getByText('Change Text')) Assert Ex: //first find the element with... const bla = screen.getByText('some string or reg ex'); //Can pass a second arg such as {exact: false} to specify whether it not the string has to be an exact match. //And of course screen has other methods that can be called on it beside just getByText. then use that element to pass an assertion Ex: expect(bla).toBeIntheDocument(); //We can use `screen` to find more than just strings and `expect` can accept args of any value for example DOM nodes, numbers, strings, Sidenote React Testing Library and DOM Testing Library and user-event testing library are all part of the @testing-library suite. @testing-library is a suite of testing utilities that provide a user-centric approach to testing web applications. It consists of several libraries that are designed to work together to make it easier to write reliable, maintainable tests for web applications. This suite is often used with the Jest testing framework Sidenote II Searching "Jest" from the US returns 1,542 results (Cypress had less) and "React Testing Library" returns 139 and 34 results were returned that contained both "Enzyme" and "testing library" although these posting typically listed "Enzyme/React Testing Library" as if they're the same thing

How is the custom provider component exported?

As a named export above the default ContextObject export

What does useImperativeHandle() expect as arguments?

As the first argument it expects the ref being passed from the forwardRef() entry. As the second argument it expects a function that returns the content (often an object) whose access you'd like to share with parent components.

What's the result (and in what form?) of calling .content on the result of calling matter(blabla)

Assuming that blabla is the content of an .md file, calling .content on the result of calling matter(blabla) will return a string that contains the Markdown content of the file without the YAML front matter.

When does getStaticPaths run?

At build time

When does the static generation form of pre-rendering generate the HTML?

At build time and then re-used for each request. In dev mode it runs on each request

What does Next use for transpiling modern JavaScript syntax to a format that can run in older browsers?

Babel // Babel is a JavaScript compiler that allows developers to use modern JavaScript features and syntax that may not be supported by all browsers, and transpile them into a format that can be executed by those browsers. // In addition to transpiling modern JavaScript syntax, Babel is also used by Next.js to enable other features, such as TypeScript support and JSX transpilation. // Transpiling refers to the process of converting code from one version of a programming language to another, usually with the goal of making it compatible with a different environment or browser. Translation refers to the process of converting code from one programming language to another. This is typically done when moving from one language to another that is better suited for a particular use case or platform.

What does the `context` parameter of getServerSideProps() contain?

Because getServerSideProps is called at request time, its parameter (context) contains request specific parameters.

Why is the second argument of a reducer function usually an object?

Because the primary purpose of a reducer function is to allow you to simply manage state based on more than one value. Side Note - Often one or more of the values comes from a component that's nested inside the component your working with.

context consume syntax

Between the component tags {arrow func that returns all the JSX and gives access to object values via the arg passed to arrow func} Ex: <ContextObjectName.Consumer> {(ctx) => {return (all the JSX which now has access to the data found in context object via ctx.specifiedPortionOfData)}} </ ContextObjectName.Consumer> Sidenote useContext and Consumer should be used sparingly for components that have very specific purposes because it can make component re-useability difficult. And potentially lead to performance loss. Sidenote context can be more concise and make managing app-wide states easier than props

How are event listeners added in React?

By adding one of the on attributes to the HTML elements opening tag and setting it equal to the desired function.

What is the relationship between the component tree, shouldComponentUpdate, PureComponent, and memo?

By default a component re-renders anytime an ancestor re-renders. The following are ways to optimize performance by preventing the default behavior. Should test performance to make sure the optimization is worth the additional complexity and potential for bugs. PureComponent prevents re-rendering unless one of the props or states changes. shouldComponentUdate does the same thing as PureComponent except lets you specify a specific prop or state change. So you specify a re-rendering only when one of the prop or state changes leads to a UI change. shouldComponentUpdate and PureComponent are used on class-based components whereas memo is used for function-based components. By default all three perform shallow comparisons. .memo allows you to pass a custom comparison func as 2nd arg if you want to perform deep comparison. Sidenote There are tools that can find performance bottlenecks and measure performance

What is one reason someone might want to use React Transition Groups instead of CSS transitions and animations in relation to React applications?

CSS transitions and animations stay present in the DOM even when they aren't visible which can slow down the aaplication.

What does an edge net do?

Caches request results near user

What does the class-based component lifecycle method componentDidMount() do?

Called when the evaluation of a component leads to it being rendered to the DOM. It essential does the same thing as useEffect with an empty dependency array

Where is getStaticProps written and how can it be used to pass static data to a page component?

Can only be used in page files but not part of the page component function itself, just in the same file. The `props` key of the object returned in getStaticProps can be used to send any data you want to the page that it shares a file with and can be accessed by that component via props. Ex: import { getSortedPostsData } from '../lib/posts'; //util function for parsing data that we created earlier export async function getStaticProps() { const allPostsData = getSortedPostsData(); return { props: { allPostsData, }, }; } //passes the blog post to the Home component as a prop so we can access it... export default function Home ({ allPostsData }) { ... } //..by destructuring the props that we passed to the home component

What are test suites?

Categorizations/groupings of similar tests. Used for organizational purposes and ease of running/stopping the tests considering large apps may have 1,000s of tests. For example all the tests regarding one feature or one component may be grouped into a single suite.

Side tangent and prompt for a few rabbit-holes

ChatGPT ? What can you tell me about multipart/form-data encoding type? A multipart/form-data is an encoding type used for submitting binary or non-ASCII data through HTML forms. It is commonly used when uploading files or submitting data that contains non-standard characters, such as characters from non-Latin scripts. When a form is submitted with the multipart/form-data encoding type, the data is divided into a series of parts, each identified by a unique boundary string. The boundary string is specified in the Content-Type header of the HTTP request, and separates each part of the data. Each part consists of a set of headers followed by the actual data. The headers include a Content-Disposition header, which specifies whether the part contains a file or a form field, and a Content-Type header, which specifies the type of data. In order to handle multipart/form-data encoding type, the server needs to be able to parse the data into its constituent parts using the boundary string specified in the Content-Type header. Many web development frameworks, such as Express for Node.js or Flask for Python, provide built-in functionality for handling multipart/form-data encoding type.

Why do we use both client-side validation and server-side validation?

Client-side validation is typically used to provide a more responsive and user-friendly experience for users by validating user input on the client-side, before it is sent to the server. This can help catch errors early and prevent unnecessary server requests, reducing server load and improving performance. However, client-side validation alone is not sufficient to ensure the integrity and security of data being submitted to the server. ChatGPT on types of validation for client and server - There are some common checks that can be put in place for client-side and server-side validation: Client-side validation: Required fields: Ensure that required fields are not left empty before the form is submitted. Data type validation: Ensure that the data entered into fields matches the expected data type (e.g. numbers, dates, email addresses). Data format validation: Ensure that the data entered into fields follows the expected format (e.g. phone numbers, postal codes). Length validation: Ensure that the length of the data entered into fields is within the expected range (e.g. password length, maximum characters in a comment box). Range validation: Ensure that the values entered into fields are within the expected range (e.g. age, price range). Server-side validation: Authentication and authorization: Ensure that the user is authenticated and authorized to access or modify the data being submitted. Business rule validation: Ensure that the data submitted by the client complies with business rules and policies (e.g. unique usernames, valid account numbers). Database constraint validation: Ensure that the data submitted by the client complies with the constraints and rules defined in the database schema (e.g. foreign key constraints, check constraints). Input filtering and sanitization: Ensure that the data submitted by the client does not contain malicious code or characters that can be used to exploit vulnerabilities (e.g. SQL injection, cross-site scripting). By implementing these checks on both the client and server side, developers can create a more robust and secure application that can handle a variety of scenarios and user inputs. Side tangent ChatGPT , validation is just one aspect of application/website security that a developer is concerned with. There are many other security considerations that a developer must take into account to ensure the security of an application or website. Some other important security considerations for developers include: Authentication and authorization: Ensuring that only authorized users can access sensitive data or perform certain actions within the application. This involves implementing strong password policies, using multi-factor authentication, and properly managing user permissions and roles. Data encryption: Ensuring that sensitive data is encrypted both in transit and at rest, to prevent unauthorized access. Input validation and sanitization: Ensuring that input data from users is properly validated and sanitized to prevent attacks such as SQL injection, cross-site scripting, and cross-site request forgery. Session management: Ensuring that sessions are properly managed and secured, to prevent session hijacking and other attacks. Secure coding practices: Ensuring that code is written securely, and that developers follow secure coding practices to prevent vulnerabilities and exploits. Vulnerability management: Regularly scanning for and addressing vulnerabilities in the application, both during development and after deployment. Compliance with security standards: Ensuring that the application meets applicable security standards, such as HIPAA, PCI DSS, and GDPR. Continued Session management: Session management refers to the process of managing user sessions in a secure way. This involves generating a unique session ID for each user, storing the session ID securely, and verifying the session ID on subsequent requests. Developers should ensure that sessions are properly managed and secured, to prevent session hijacking and other attacks. This includes implementing mechanisms such as session timeouts, secure session storage, and proper session termination. Secure coding practices: Secure coding practices are coding techniques and patterns that help prevent vulnerabilities and exploits. This includes practices such as input validation and sanitization, parameterized queries, using secure cryptographic algorithms, and using prepared statements. Developers should be familiar with these practices and follow them when writing code to prevent common vulnerabilities such as SQL injection, cross-site scripting, and buffer overflows. For point 6, there are many vulnerability scanners available that can help developers scan for and identify vulnerabilities in their applications. Some popular vulnerability scanners include: Nessus Qualys Acunetix OpenVAS Burp Suite However, it's important to note that vulnerability scanners should be used as a supplement to manual security testing and not as a replacement. Developers should always perform manual security testing to identify vulnerabilities that may not be caught by scanners. For point 7, knowledge of applicable security standards is typically required by each individual developer, as each developer should be responsible for ensuring that their code meets the necessary security standards. However -- Manual security testing is typically performed by security professionals who specialize in security testing, such as penetration testers or security consultants.

Consider rendering multiple instances of a component each using unique data. For example, a list of items in a cart. You want an onlClick for each component instance to trigger a unique details page associated with that particular item. How would you specify a dynamic route to match the various instances of the component -- from within the configureBrowserRouter entry and from within the component?

Colon, map, key prop, string template literal, useParams. App component, page component, item component. //There are different appraoches but the above is for React Router. In general You have an item component that can be populated with data (an object), these objects are added to the cart (array), the object that's used to populate each component has something like an id property that can be used in the Link that's associated with it to set the dynamic portion of the route when clicked, the dynamic portion of the URL is obviously what's used to determine which particular details page to display. In short, : says hey this segment of the path is going to be dynamic. String template literal sets the dynamic portion of the path equal to a UID for each item (block of data) that it's looping over with map. useParams accesses the current value for the dynamic path segment which just so happens to be the UID for individual blocks of data and uses it render each component instance dynamically by populating it with that data. //App file {path: "/products/:productID", element: <BlaComponent/>} //Page file import {useParams} from ''react-router-dom'; const params = useParams(); params.productID //List file const products = [{id: uniqueId, title: Blabla}, {}, {}, etc]; return ( <ul> {products.map((prod) => { <li key={prod.id}> <Link to={`products/${prod.id}`}> {prod.title}</Link> </li> }) </ul> )

Terms and ideas to look into further in the future

Compiler, translator, interpreter, execute, translate, processors, types of environments, bundling, containers, DOM, XHR, W3C, SEO, SERPS, API, Web Socket, JS statements vs Expressions, up-to-date encryption algorithms and their implementations, prototypes,

What are two props received by the App component by default?

Component and pageProps Ex: export default function App({ Component, pageProps }) { return <Component {...pageProps} />; }

What is react context?

Component wide, behind the scenes, state storage. So you don't have to pass state from a component through other components that don't need to do anything with that information just to reach another component that does need the information. It increases efficiency and decreases CPU cycles.

What is `React.PureComponent`?

Convenience component used for performance optimization of class-based components. Similar to shouldComponentUpdate() but does the comparison for you behind the scenes. shouldComponentUpdate allows for more specificity because you can do the comparison manualy by accessing specific props and and states to determine re-rendering rather than checking all of them at once behind the scenes as is the case with PureComponent. Sidenote - Both options only do a shallow comparison so you're wouldn't want to use it for states and props received are objects or arrays without adding special syntax. Because obj and array references changes with every re-render even if the contents don't change. A shallow comparison doesn't check the content of nested objects and array, only whether the reference the same place in memory.

What are Core Web Vitals? More of a computer science or SEO question

Core Web Vitals are the subset of Web Vitals that apply to all web pages, should be measured by all site owners, and will be surfaced across all Google tools. Each of the Core Web Vitals represents a distinct facet of the user experience, is measurable in the field, and reflects the real-world experience of a critical user-centric outcome. Used to determine search rankings. Currently includes - loading, interactivity, and visual stability—and includes the following metrics: Largest Content Paint (LCP aka loading), First Input Delay (FID aka user interactivity), Cumulative Layout Shift (CLS aka visual stability) //When I create my web sight I should check these metrics and make sure there within an acceptable range/threshold

What are four approaches to making the state of an auth token available app-wide?

Could use createContext(), Redux, Redux Toolkit, or React Router functionality.

Describe creation process of a hook. What should it return?

Create js file for the hook typically contained in a "hooks" folder on the same level as the components folder. Write it just like any other function with exception of name. Import into file that you want to have access. return any variable or object containing variables created in the hook if you want to have access to them in the JSX of the files that use will the hook.

Provide an example of creating a context object and use its syntax to describe the various peices

Creation example from bla-context.js file - import React from 'react'; const ContextObjectName = React.createContext({someState: defaultValue, someOtherState: defaultValue2}); export default ContextObjectName; Sidenotes ContextObjectName isn't a component, it's an object, but we name it the same way because it will contain a component when it's used as wrapper.

What are static assets?

Data that isn't dynamic such as an image or title of a page.

Common Authentication tech for blockchain websites that use React

Decentralized Identity systems (DIDs) such as Ethereum Name Service (ENS) or uPort (might be worth looking into further) traditional authentication methods such as OAuth or OpenID Connect, which allow users to authenticate using their existing social media or email accounts. built-in authentication and identity management features, such as Ethereum Wallet and MetaMask

Method Two for Defining Routes with ReactRouter (old version)

Define the routes in components' JSX code instead of JS objects in an array. //Route is component import {createRoutesFromElements, Route} from 'react-router-dom' //wrapper Route around nested Route const routDefinitions = createRoutesFromElements( <Route> <Route path="/" element={<Home/>} /> </Route> ); const router = createBrowserRouter(routeDefinitions)

What is debouncing?

Delaying the call of a function until a specified inactive time period has passed. This is done to avoid unnecessary CPU cycles.

How send an authentication token along with an http request?

Depends on the backend logic but most likely add something to the meta-data of the fetch (2nd arg). header meta-data does the trick in this Ex: fetch('someURL' + desiredParam, { method: request.method, header: {'Authorization', 'Bearer ' + tokenNameOrFuncThatRetrivesTokenName} } ) Sidenote 'Authorization" is the header, 'Bearer' is the header format,

What does describe() expect as args?

Description of the category that this suite contains (string as first arg). Second arg is an anonymous func that contains the all the test() funcs for that suite.

YAML Front Matter can be parsed from a local markdown file using what duo of functions/modules?

Details of func aren't required to understand Next.js but the `fs` is imported along with `matter` to create a utility func to parse data from the file system for example the title which could be used to set a dynamic param value for the URL.

What should we keep in mind when updating a state slice within the reducer function associated with a Redux store if we're not using redux toolkit?

Do not directly mutate the state because it may lead to bugs. Instead return a new state object, spread the old state, and update the property (from initialStateObj for example) that you wish to updated. Ex: NOT if (action.type === 'increment') { state.count++ } NOT if (action.type === 'increment') { state.count++ return {state} } INSTEAD if (action.type === 'increment') { return { ...state, state: state.count + 1 } } Sidenote State slice refers to the entire inititialStatteObj associated with a given createSlice function call. The inidividual values in the object are states. multiple state slices are brought together in the store for app-wide state.

What must be done to enable a component to be a wrapper?

During the creation of that component you must pass {props.children} between the opening and closing top level element tags.

What do curly braces indicate in JSX?

Dynamic input

What are query parameters? What are they often used for (list 6)?

Dynamic portion of the URL following a question mark. Search and filter data. Pagination. Tracking. Authentication. Sharing. sending data to be stored. Elaboration of practical use-cases - Search and filter data on server or webapp such as specify filters such as date range, category, or price range. Pagination - might use a page parameter to specify the current page number, and a limit parameter to specify the number of items to display per page. Tracking - generate unique tracking code as query param for user when they take actions such as clicking a link. The unique identifier can be used to identify the user and the actions they took. We can store the tracking code on the server/database and through data analysis track how many users are clicking on specific links or buttons in your web application, and how many of those clicks are resulting in a specific action or conversion. In this context, "conversions" refer to a specific action that you want users to take on your web application, such as making a purchase. //The server can associate that tracking code with the user's session or other identifying information (such as an IP address or user agent). Authentication -For example, a user might receive an email with a link containing a unique token as a query parameter, which can be used to authenticate the user and grant access to a specific page or feature. Sharing - For example, a link to a specific product page might include a query parameter with a reference to a specific user, which can then be used to personalize the product recommendations or pricing.

What should we keep in mind about Await in regard to children?

Each Await is designed to have a single child.

Notes Vid 34

Each React component may only contain a single top level element. If the desired end result is to display two elements side by side there is a workaround. You can implement the workaround by wrapping the two elements within an additional div or other element. For easier readability when nesting JSX elements, use parentheses around the entire snippet.

What is meant by next.js does code splitting automaticaly?

Each page only loads what's necessary for that page. That means when the homepage is rendered, the code for other pages is not served initially.

What does useRef() do? What are some task it can be used for? Provide example where it is used to focus on an input when a button is clicked.

Enables the direct access and manipulation of the DOM. Returns a mutable object with a single property, `current`. The current property can be used to store values across renders (saving values), share values between components (with the help of .forwardRef), and accessing DOM elements to perform operations (auto focusing, clearing input, monitoring keystrokes). import React from 'react'; function Example() { const inputRef = React.useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input type="text" ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </> ); } Sidenote you could modify the import entry to be import {useRef} from 'react'; and then be able to useRef() without prepending with React.useRef() You could also pass nothing to useRef(null). useRef() would initialize the `current` object to `undefined` which is acceptable.

What is the purpose of SPA routing?

Enables the use of links to route a user to views (illusion of pages) other than the default view of Single Page Application (SPA)

What simple logic can be used to toggle between two states to determine whether a component is displayed?

Ex 1 import React, { useState } from "react"; function Example() { const [showComponent, setShowComponent] = useState(false); return ( <div> <button onClick={() => setShowComponent(prevShowComponent => !prevShowComponent)}> Toggle Component </button> {showComponent && <MyComponent />} </div> ); } function MyComponent() { return <div>This is my component</div>; } export default Example; Ex 2 const [showCart, setShowCart] = useState(false); const showCartHandler = () => setShowCart(!showCart); return ( <Fragment> {showCart && <Cart onClose={showCartHandler} />} <Meals/> </Fragment> ) Sidenote - The prop would be sent and attached to buttons

What do we use to statically generate HTML with data?

Export an async func called getStaticProps (runs at build time to fetch the external data for the pre-render to be stored on the CDN). props can be returned in this function and passed to the component function Ex: export default function Home(props) { ... } export async function getStaticProps() { // Get external data from the file system, API, DB, etc. const data = ... // The value of the `props` key will be // passed to the `Home` component return { props: ... } }

How can you use server-side rendering?

Export getServerSideProps from a page component rather than exporting getStaticProps. Ex: export async function getServerSideProps(context) { return { props: { // props for your component }, }; }

Step 2 Explain the following lines found in the index.js file.. Line 1 - import ReactDOM from 'react-dom/client'; Lines 2 & 3 - import './index.css'; import App from './App'; Line 4 - const root = ReactDOM.createRoot(document.getElementById('root')); Line 5 - root.render(<App />);

First 5 lines of a react app index.js file. 1) The react-dom/client library automatically comes along with the react library when we run the npx. We still need to import it to the file where we want to use it though. In this case we saved it to a variable called ReactDOM. 2 & 3) Imports the App.js and index.css file found in the src folder with the index.js file. App is a component. 4) creates a variable called 'root' from calling the 'createRoot' method on the 'ReactDom' object and passing an html element (with the ID of 'root') in as the argument. This creates the main entry point/hook of the overall UI that we'll be building. 5) Specifies what should be rendered in the html element that we specified in line 4. In our case we're rendering the app.js file that we imported in line 3.

What are 4 commonly used properties on the fetcher obj?

Form, load, state, submit //Not to be mistaken with the `Form` component and `submit` function that we imported directly in previous lessons.

What is the first arg from the func returned from useSubmit wrapped in when passed to the action? How can it be accessed from the action?

FormData obj which we can destructure/unwrap by using request.formData() in the action.

Section 9 video 99

Fragments, portals, and refs Portals help create a cleaner DOM

Where would a static image file be served from in Next.js?

From an `images` directory inside the `public` directory //images isn't a special folder, could be named anything. public is a special folder

From what folder can we serve static assets in Next.js?

From the top-level public directory (can be nested within)

Where shouldn't we fetch an API Route? Why?

From within getStaticProps or getStaticPaths because getStaticProps and getStaticPaths never run on the client side

Which HTTP method does fetch use by default?

GET

What is a good use case for an API route in Next?

Handling Form input Full CRUD

describe state batching

If a single function calls different state updates consecutively within a synchronous code snippet, rather than re-rendering the entire component twice it will just re-render the component once and put the two different state updates in one batch. Sidenote if a time delay in a synchronous function was called between the two state updates then they may not be batched. It also might not be batched if the function is asynchronous.

When setting the style prop on an element, what is the difference between a CSS style name that has a "-" and one that doesn't?

If the original CSS property name contains a hyphen, when listing it in the "style" entry we encase it in '' or "" or remove the hyphen and make it camelCase.

Why wouldn't we just use setTimeout directly in the useEffect in the previous card?

If the user reloads the page the useEffect will run again and reset the timer even though the timer for the token expiration on the backend doesn't reset because they weren't required to login again in this scenario.

How can the array assigned to the id key in the previous example be accessed from getStaticProps

If we destructure params then params.id if not context.params.id

What is a convenient sidenote for writing the default values in the context object?

If you add default values the IDR will provide autocomplete functionality

What imperative alternative does react-router-dom offer for using a <Form> to trigger an action in a createBrowserRouter route definition?

Import and use the `useSubmit` hook from react-router-dom.

How can you access dynamic route params from within getStaticProps

In Next.js, you can access dynamic route parameters from within getStaticProps by using the context parameter. The context parameter is an object that contains information about the current request, including the dynamic route parameters. To access the dynamic route parameters, you can use context.params. For example, if your dynamic route has a parameter named id, you can access it in getStaticProps like this: javascriptCopy code export async function getStaticProps(context) { const { id } = context.params; // use the id parameter to fetch data or perform other operations return { props: { // return the props object }, }; } // The context parameter is an object containing the following keys: params contains the route parameters for pages using dynamic routes. For example, if the page name is [id].js , then params will look like { id: ... }. You should use this together with getStaticPaths, which we'll explain later. preview is true if the page is in the Preview Mode and undefined otherwise. previewData contains the preview data set by setPreviewData. locale contains the active locale (if enabled). locales contains all supported locales (if enabled). defaultLocale contains the configured default locale (if enabled).

From where can global css styles be imported

In Next.js, you can add global CSS files by importing them from pages/_app.js. You cannot import global CSS anywhere else.

What can you return with a loader? What is the recommended return?

In a loader, you can return any form of data you want including the Response obj that's automatically created for you and saved to the variable associated with fetch, any other built in objs, custom objs, etc... However, here's a quote from the docs "While you can return anything you want from a loader and get access to it from useLoaderData, you can also return a web Response." "If you're planning an upgrade to Remix, returning responses from every loader will make the migration smoother.".

What is one approach to auto logging out a user and removing expired token from local storage?

In action post credentials store returned auth token store new Date for expiration to match backend token expiration //don't forget to remove these from storage in the logout function In util/auth.js check for presence of token in storage new Data .getTime() subtracted from expiration date if no token return null if subtracted dates is negative return "EXPIRED" else return token variable In RootLayout Component useEffect if token absent return if token expired useSubmit to trigger logout and return Elaboration - In the action where we wrote the logic to send credentials, receive token, and store token, we also create a date for one hour in the future and store it. expiration.setHours(expiration.getHours() + 1); localStorage.setItem('expiration', expiration.toISOString); //built-in browser features //Sidenote would need a different approach if had sibling RootLayouts. //.toISOString converts a Date object to a string representing the date in ISO 8601 format YYYY-MM-DDTHH:mm:ss.sssZ In the utils/auth.js file create a function to check the duration of the token by creating a current date and subtracting the expiration date that we put in storage earlier from the action function. // New Date() as a stand-alone would return the current date. // We called .getTime() on their values when subtracting because we only care about the hours, seconds, minutes, in this case rather than the date and we don't want to start of a new day to throw things of Then in the helper function that's used to check the overall status of the token throughout the app -- We check to see if the token is in storage, if not, return null. Then we check if the duration is < 0, if so return "EXPIRED" else return token (value retrieved from storage with .getItem(keyName) We use the returned value of this function in the useEffect of the RootLayout component to log the user out when the token is expired. if (!token) {return} if (token === "EXPIRED") {useSubmit hook to log user out} return token

Where might the logic for something like retrieving a token from storage be written considering it's used in many places?

In an auth.js file in a utility folder

What is the result of returning `fallback: blocking` within getStaticPaths

In short If there's a new content then it wasn't generated at build time. fallback: blocking makes it so the 404 or fallback page isn't render while waiting for said content to be generated on the server at request. Afterwards, the result is cached so it only happens once per route Quote from docs If fallback is 'blocking', new paths not returned by getStaticPaths will wait for the HTML to be generated, identical to SSR (hence why blocking), and then be cached for future requests so it only happens once per path. getStaticProps will behave as follows: The paths returned from getStaticPaths will be rendered to HTML at build time by getStaticProps. The paths that have not been generated at build time will not result in a 404 page. Instead, Next.js will SSR on the first request and return the generated HTML. When complete, the browser receives the HTML for the generated path. From the user's perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, like other pages pre-rendered at build time. fallback: 'blocking' will not update generated pages by default. To update generated pages, use Incremental Static Regeneration in conjunction with fallback: 'blocking'. Note: fallback: 'blocking' is not supported when using output: 'export'.

Using the last scenario how do we also make the URL of the action dynamic based on whether it starts with the NewEvent or EditEvent component.

In short use the current request.method value which we already set to be dynamic between the two to determine which url to use. Different ways this could be done but the following is one example. let url = 'https://someURL'; method = request.method; if (method === 'PATCH') { let url = "https://sameURLAsOther/" + params.eventId }; From action logic - let url = 'https://someURL' //So the above url will be used as a default and we'll let our default case be the NewEvent which uses the post method. //The case of PATCH in the following matters because when form passes the `request` obj to the action, the `method` prop value is automatically converted to all caps even if we passed it as lower case from the Form opening tag. Destructure request then method = request.method then if (method === 'PATCH') { let url = "https://sameURLAsOther/" + params.eventId } Of course we need to add the action prop to both components' route definitions.

Describe the process and syntax for adding a test for an async function to the suite. List 3 key points. Video 409 provides a good walk through.

In short we want the second arg of the describe() func to be async, we want to await the use of the `screen` obj and use one of the `find` methods on `screen` because they return a promise and allow us to specify a time limit for it to resolve. Long explanation import {render, screen} from '@testing-library/react'; import Bla from './Bla' //Bla being the component you want to test. //use the describe func to create a suite. First arg is a string that should make it easy to identify this suite. Second arg is an anonymous func that contains a bunch of test() funcs. Both are global variables from the Jest framework so we don't have to import them the same way as render and screen Ex: describe('label to describe this suite', () => { //Test expects two args -- a string description to easily identify the test and an anonymous func that does two or three things, 1 renders what you want to test, the `Bla` component in our case. 2 - Act logic in needed (not necessary in bellow example). 3 - Assertion (use `screen` obj methods and `expect` func along with one of its methods). Since we're testing async code we'll also wont the func that we pass to test to be async Ex: test('label to describe test', async () => { render(<Bla />); //use a method on `screen` to access to various part of the component and save it to const. If we're testing an async func we'll use one of the `find` methods instead of `get` because `get` would throw an error whereas `find` returns a promise. And of course we want to await that ptomise so we can write it n our assertion. In this case we'll use findAllByRole which expects something like 'button' or 'listitem'. We used the `All` version of the method because we expect multiple `listitems`s in the component. Because we're testing an async func and using a find method on screen we could add a third arg to the method to specify a time limit for the promise to be resolved unless you want the default of one second. Ex: const listItemElements = await screen.findAllByRole('listitem', {exact}, {some time specifcation not sure about format}); //now we use the variable just created to make an assertion by using the `expect` funct. Ex: expect(listItemElements).not.toHaveLength(0); }) })

Maybe look further into this when I actually care about styling. Sidenote on using the clsx library rather than a ternary expression to toggle between css classes. Can reference Next.js official site tutorial under the styling tips section of the metadata section.

In some cases it can be more concise (less code), flexible (use more than one condition to determine the class), and compatible (works well with other css frameworks and libraries such as Bootstrap and Tailwind) npm install clsx import {clsx} from 'clsx'; <div className={clsx({ [styles.success]: type === 'success', [styles.error]: type === 'error', })} > ChatGPT The clsx library is often used in React applications to conditionally apply CSS classes to a component based on the state of the component or the props passed to it. While it is possible to achieve similar functionality using a ternary expression or other conditional logic, clsx provides a more concise and flexible way to handle multiple class names. Here are some reasons why someone might prefer to use clsx over a ternary expression: Conciseness: clsx allows you to combine multiple class names into a single string, making it easier to manage and read. For example, instead of writing className={isActive ? "active" : ""} for each possible class, you can use clsx({ active: isActive }) to achieve the same result with less code. Flexibility: clsx allows you to pass in multiple arguments of different types (such as strings, arrays, objects, or functions) and it will concatenate them into a single string of class names. This makes it easy to handle different use cases, such as toggling classes based on multiple props or dynamic values. Compatibility: clsx works well with CSS frameworks and libraries, such as Bootstrap or Tailwind CSS, that use complex class name patterns or require specific class name conventions. It also works with legacy code or third-party components that use different naming conventions for classes. Overall, while a ternary expression can be a simple and effective way to toggle CSS classes based on a single condition, clsx provides a more robust and flexible solution for managing class names in a React application.

Where do we handle errors from loaders?

In the component associated with the closest errorElement prop?

In a Next.js app where is the _app.js file located by default? What is it used for? What props does it receive by default?

In the pages folder. Root component. Sidenote - good place to add stuff like a universal layout component. But Next.js 13 handles layouts differently. It receive the `Component` and `pageProps` as props. Sidenote - Next..js passes these props automatically behind the scenes.

Where are test files typically written?

In the same folder as the files they're used to test

Video 124 Recap

In this video we took the login and logout logic from the App file and entered it into the auth-context file. We went to the other files where those props were being used, imported the AuthContext object, replaced props with the variable we set using the useContext() hook. Imported the named AuthContextProvider component from the auth-context file, wrapped the app component tag found in the index file with the AuthContextProvider component.

What should we import bla.module.css as when working with Next.js?

Industry standard is to import it as "styles" not classes as demonstrated in the course.

Section 26 Testing React Apps (Unit Tests)

Introduction to testing with React Testing Library and Jest

What does the loader do to promises returned in it and what impact does this have on the code we write in it (use fetch for an example)?

It automatically returns the resolved form of promises contained within it. For example a fetch would resolve to a Response object (built in JS obj) without us manually chaining any .thens to transform the data from json to a JS obj.

By default which action is triggered by the submission of a Form? How can you specify an action other than the default?

It automatically triggers the action function of the currently active route unless you manually specify another route by using the action prop in the opening Form tag.

Once the desired data is parsed from a markdown file what can be done with it? And how

It can be added to the desired page (hydrate or populate the html I think) using a next.js data fetching method called getStaticProps()

Module 11 has the second largest project in this course

It could be a good idea to attempt building it on my own after completion of the course.

What does the `action` property of a route definition expect as a value? What is it used for?

It expects a function containing a fetch with a method other than GET (loaders are used for GET). "Route actions are the "writes" to route loader "reads".". Used to mutate data.

What is the useMemo() hook syntax?

It expects a function to be returned as its first argument. The function whose results you want stored. As a second argument it expects an array of dependencies. Ex: const blaBla = useMemo(() => { return props.items.sort((a, b) => a - b); }, [props.items]); Important - In order for the above entry to work as intended -- the useMemo() hook would also need to be applied to the items array that is being passed to this component from the other file. this is because ever time the code is re-evaluated a new arrays and objects are recreated even is the contents remain the same. So it would register that the props.items did update even if the content didn't just because the new array wouldn't triple equals the old array, it would only double equals or something like that. Ex: <DemoList items={useMemo(() => [5, 3, 7, 10, 9], [] )} /> Sidenote this entry doesn't have dependencies so we just use an empty array as its second argument Sidenote 2 useMemo() isn't used nearly as frequently as useCallback()

What is the result of using `...` within the dynamic potion of a filename? Ex: /pages/posts/[...id] How does this changed what we should return as the value for the id key in getStaticPaths?

It extends the dynamic route to catch all paths Ex: /posts/a & /posts/a/b and /posts/a/b/c We should make its value an array rather than for example just id: fileName.replace(/\.md$/, ''),

How is the Script component from next better than the default html script element?

It helps avoid render blocking by scripts

What should we keep in mind when installing Redux Toolkit?

It includes the Redux Library as part of its install so you don't have to install both separately. If you install it after vanilla redux has already been installed I think you can remove the duplication from the dependencies folder.

How does useContext() change the frequency for which the content passed to it is evaluated?

It is re-evaluated when the associated context object changes as well as when it's personal state changes.

What does useImperativeHandle enable?

It is used to CUSTOMIZE the instance value that is exposed to a parent component by React.forwardRef() and utilized by useRef(). Sidenote Emphases on customize because if you're not customizing with local logic such as state, function, obj, etc.. you might as well just use the forwardRef() and useRef() duo

what does the useCallback() hook do? What is it used for? How is it implemented?

It memorizes the encased func (1st arg) rather than creating a new one with each re-render. It's used to prevent the re-rendering of children components who receive the func as a prop. It accepts an array of dependencies as its second arg. The func won't re-render unless one of its dependencies change. As dependencies you should add the variables that the function uses with the exception of built-in funcs' variable names setState variables. const handlerBlaBla = useCallback( () => { console.log('bleble'); }, []; );

What approach should be taken when exporting a page component in Next.js?

It must be exported as default Ex export default function FirstPost() { return <h1>First Post</h1>; }

What needs to be done to use the context once is it created?

It needs to be provided and hooked into

What does calling redirect return? What does it expect as an arg?

It returns a Response object that redirects a user to a different page. It expects the path of the page (URL) you want to direct the user to upon completion of the action. Ex: redirect('/blabla') redirect() is a shortcut for... new Response("", { status: 302, headers: { Location: someUrl, }, });

What does the json() fetch utility from react router return? What does it accept as args?

It returns a new Response object based on the JSON data and possible meta data that are passed to it as first and second args respectively. Ex of use return json(data, { status: 200 });

What should we keep in mind about the isActive prop of a NavLink component?

It returns true or false based on whether the begging of the currently action route matches the to="" prop in NavLink. It can be used to apply CSS classes to the NavLink dynamically using a ternary expression. Elaboration If you specify <NavLink to="/" className={({isActive}) => (isActive ? someCSSClass : undefined)} and you click the link associated with "/" -- it becomes active but then you click on the to "/products" path and then both links will show the active class. This feature exist so that the link can be treated as active even if we are on some nested child route. But can be a problem if links to both paths are visible on the same page

What is the purpose of adding the `loader` property to a route definition in createBrowserRouter? What does it expect as an value? Where can its return value be accessed?

It sends the fetch request for data used by a component before the component is rendered for the first time rather than after component is rendered for the first time. So it loads faster. It expects an async function with fetch logic. You can use the data returned in any component or any custom hook via useLoaderData and useRouteLoaderData Sidenote - one way to access said data is the useLoaderData hook `import {useLoaderData} from 'react-router-dom'` //executing the hook will return data from the closest loader const bla = useLoaderData() //now `bla` represents whatever data was returned. What if there's more than one loader?? Sidenote The createBrowserRouter function is called in the App file and is what contains the route definitions including loaders. However, it makes more sense to put fetch logic in the file of the page that it's fetching data for so we could write the logic their, create an named export/import duo, and use the import as the value for the loader in the rout definition. By putting the logic in the associated page file it keeps the component file and the app file lean.

What makes a path an absolute path?

It starts with a "/"

How does Next.js optimize the use of css modules?

It' implements code splitting for them ensuring that the minimum amount of CSS is loaded for each page resulting in smaller bundle sizes and faster load times

What is the purpose of creating a custom provider component?

It's cleaner because you can use to write logic such as handlers that are associate with the states contained in the context object and you only have to pass the value={{}} prop once.

What is the purpose of Redux?

It's similar to React context but offers easier scalability, greater predictability, and middleware options which can be useful for larger more complex apps. Redux can also be used with other UI libraries, not just React. Help manage cross-component or app-wide state similarly to context. Both avoid excess prop chains/prop drills. Sometimes both are used within the same application.

What is getStaticPaths used for? How does this differ from getStaticProps?

It's used to implement dynamic URLs. Pre-render pages with paths that depend on external data. getStaticPaths is used when the page path depends on external data whereas getStaticProps is used when the page content depends on external data. //built -> external data fetched -> page generated with path to match /posts/[ID]

Where are redux-related code files typically stored?

JS file in a folder called store on the same level as the components folder

How can you transform a particular JavaScript object property (key and value) to a JSON string?

JSON.stringify({desiredKeyName: objName.key, etc...}) If you were to use JSON.stringify(objName.keyName) only the value associated with the specified key would be stringified

What is JSX?

Java Script XML - A special syntax evented by the React team for embedding html into js more conveniently. Uses declarative rather than imperative.

Section 14 Vid 173

JavaScript code running in the browser should never directly access a database. It would be highly insecure because the database credential would be exposed. Any JS running in the browser is exposed to the end user. Browser talks to backend server (Backend API) and then that server or API retrieves the data from the database and returns it to the browser. The backend application often runs on a separate server and uses a backend server language such as PHP, Node.js, ASP.net, etc.. Backend code can't be viewed by the end-user. API - pretty much means different entry point lead to different results. We typical use one of two standards for server APIs - REST or GraphQL

What is lazy loading?

Loading certain pieces of code only when they're needed to improve performance by reducing initial bundle size so the app/website will be faster. React Router has a new version of the lazy function but the course hasn't updated to use it yet and I don't fully understand it so the following is the old way using the func from react rather than react router. Instead of - import {loader as BlaLoader} from '../blabla'; etc.. etc.. use import {lazy, Suspense} from `react`; import {createBrowserRouter, RouterProvider} from 'react-router-dom'; //Added the second import to emphasize that this example is using the lazy() from react and not react router. const Bla = lazy(() => import('../blabla')); //overall page import element: <Suspense fallback={<p>Loading...</p>}> <Bla/> </Suspense> //The first dynamic import (overall page import) added as the component for the element prop in a route def and wrapped by Suspense loader: () => import('../blabla') .then(module => module.loader()) //The loader prop of the route def imports the loader from the same page or loader: ({params}) => import('../blabla') .then(module => module.loader(params)) //If the loader uses params. Or you could pass the `meta` object which contains both the params and the request. ChatGPT Lazy loading is a technique used in web development to defer the loading of non-critical resources until they are actually needed. This technique is especially useful for larger applications or web pages that have a lot of content, such as images, videos, or scripts. In the context of React Router, the lazy() function allows you to lazily load a route component, which means that the component will not be loaded until it is actually needed. This can help improve the performance of your application by reducing the initial bundle size, since the component will not be included in the initial bundle.

What are three separate displays you may want to prepare for a component which renders a response?

Loading, returned data, error

What are local markdown files?

Local markdown files are markdown files that are stored on the local file system of a computer or a server. Markdown is a lightweight markup language that is commonly used to write formatted text that can be easily converted to HTML.

What are the top React styling libraries in 2023? I'll look into one of these if I feel like it closer to employment. What do the companies I'm interested in use?

Material-UI (best for general purpose) Ant Design (AntD) (best for enterprise applications) Chakra UI React Bootstrap Blueprint (best for data-dense desktop applications) VisX (low-level visualization components) Headless UI (React version) Retool (best for internal applications) Semantic UI React Evergreen Grommet Rebass (lightweight) Mantine Next UI (beta) ThemeUI PrimeReact

What is "Matter" with a capital M?

Matter is the underlying library that gray-matter is built on top of. It provides a way to parse and manipulate front matter from any file format. //Not the same thing as matter()

Where might we store markdown files in our file system (file structure)?

Maybe a top-level folder named besides one of the special like `public` or `pages`. A common name for the folder might be `posts`

What might we find at the top of a markdown file and in what form?

Meta data in the form of YAML Front Matter Ex: --- title: 'Two Forms of Pre-rendering' date: '2020-01-01' ---

React-Router

Most popular routing library for React applications. Provides the illusion of routing. Used to give a SPA react app the feel of an SSR app in regard to having links direct users to different views AKA different URL paths = different displays. Also simplifies work with http requests. npm install react-router-dom

What is the lifecycle of a page by default? What is the lifecycle if the route being navigated to has a loader? What is the lifecycle if the route being navigated to uses fetcher.load? What if the page doesn't have a loader in it's route definition and doesn't use fetcher.load but an ancestor has a loader?

Navigation event -> render -> load data -> re-render Navigation event -> load data -> render data loaded when specified by fetcher.load -> navigation event -> page rendered If you're using a page component that doesn't have a loader assigned to its own route definition, but a loader is assigned to a parent or ancestor route definition, the data will still be loaded before the page is rendered. This is because React Router triggers the loader of the parent or ancestor route definition before rendering the child components.

In general why would someone use an API route rather than getStaticProps or getServerSide props?

New Answer Data isn't available at built. Don't want it to run for every requests. //API routes can run on client side or server-side Old answer In general, if you need to fetch data for a client-side application, use an API route. If you need to fetch data for server-side rendering, use getServerSideProps. getServerSideProps is a method in Next.js that runs on the server-side and fetches data for the page during runtime. This means that the data is fetched every time a user requests the page. In contrast, an API route can be used to fetch data on the server-side or the client-side, but the data is fetched separately from the page request. If the data is ready at build use getStaticPops

Sidenote - Explain what we did with fs.readdirSync(dirName) (a node function) along with .map, .replace, and a reg ex, in relation to getStaticPaths, getStaticProps, params, and paths // Probably best to skip and re-write this question at the end of the current Next.js tutorial section so I can tie it all together when it makes more sense..

New Answer off the top of my head.. could be wrong or missing something but this is my current understanding of the process... We used fs.readdirSync to create an array containing the markdown filenames from the specified dir. We then mapped over that array and used .replace and a reg ex to replace the .md extension with an empty string. We used the result of this along with getStaticPaths to specify the acceptable dynamic path segments. We then used the params prop which is automatically passed to getStaticProps to retrieve the current value for the dynamic path segment and used path.join to add the .md extension to the params so that we could use the path to specify which .md file to use fs.readFielSync on to pre-render a hydrated. //array of objects with params key pointing at nested object whose key is the dynamic path segment pointer (not one of the accepted values, just the place holder) //Must be returned as the `paths` prop in getStaticPaths(){} Original answer from when "getStaticProps, and params" that part of the question was left off... We created the following function and returned the result of calling the function inside getStaticPaths(){} export function getAllPostIds() { const fileNames = fs.readdirSync(postsDirectory); return fileNames.map((fileName) => { return { params: { id: fileName.replace(/\.md$/, ''), }, }; }); } //So that the array returned from .map matches the shape of the array returned from calling fs.readdirSynce -- it must contain objects that have the `params` key as seen above and the and the params key must have an object as a value that contains the `id` key because `id` is what we used as a pointer to the dynamic path segment in question by using [] when naming the file. The value of the `id` keys are the markdown files' name that we use to populate this dynamic `id` page. //The reason we create this new array by mapping over the array from fs.readdirSync is to use a reg ex to .replace the .md extension from the `id` property value with an empty string because the getStaticPaths function won't work properly if we leave the .md extension. What we did with the funct 1) export async function getStaticPaths() { const paths = getAllPostIds(); return { paths, fallback: false, }; } //must be name `paths` can't just name it blabl //`paths` ignore `fallback: false` for now

What is a Thunk? What is the idea behind using it in relation to Redux?

New answer A function that delays the evaluation of an expression. Update state after mutating data from a fetch. Old answer In the context of Redux Thunks are used to write asynchronous logic that relates to the store. Thunks are typically used to dispatch actions that make API requests. This keeps the useEffect entries contained in the component files lean and enables more expressive and composable code. In one example we retrieved data from the database (backend API), performed some logic on the data, and updated the state of the Redux store with it. We specified when to execute this Thunk by dispatching it within a useEffect hook located in the App component file. In another example we used a thunk to dispatch an action that would trigger a change in the UI to indicate success, loading, or error, based on the status of a fetch used to add an item to a cart. Ex of a Thunk: const sendCartData = (cartData) => { return async (dispatch) => { //logic for fetches, dispatches, sideEffects, maybe some error handling, etc.. } } Sidenote The Thunk function in our examples were dispatched from within a useEffect contained in the App component Ex from within useEffect: dispatch(sendCartData(cart)); cart is selector value that we obtained with useSelector. Sidenote II When it's executed it receives the dispatch argument automatically for the return async (dispatch) => {} portion of the code. Sidenote III Sometime created in the same file as the slice that it's associated with. Thunks may be contained in their own files within the store folder and named the same thing as their associated slices along with appending "actions".

What are two question we want to ask ourself when embarking upon the testing process? Which type of test is written first and when it it written? What three outcomes/cases do you want to test this code for?

New answer Scope of the test and which technologies to use (such Jest and React Testing Library) Unit tests are often written before the code that they test (test driven dev TDD) success, failure, edge (performance optimization metrics) Old answer Two questions What do you want to test? How do you want to test it (what kind of code should we put into our testing code what library/framework)? Unit test are written first and are small focused tests so that you write directly after the code that you want tested so if something does go wrong it's obvious what is it. In test-driven development they are written before the code that they test. You want to test success and error cases as well as rare but possible cases.

What is a popular framework for automatically pre-rendering pages, blending client-side and server-side code (fetching data on the server and rendering finished pages), server-side storing data, getting data, and authentication for React apps?

Next.js

In Next.js what might you use in place of <img src="/images/profile.jpg" alt="Your Name" />

Next.js provides an Image component out of the box to handle stuff like image optimization for you out of the box so it better than the default html approach.

What is one difference between the "public" folder in a standard React App and a Next.js App? Why?

Next.js public folder doesn't contain an html file by default. Next.js has built-in pre-rendering so the SPA is automatically pre-rendered when the request reaches the server (or when we specify).

Do custom component opening tags have access to built-in React properties such as className?

No

If a function is created using const, can it used in a line above where it be was created? What about if it was created using the function keyword?

No Yes because of hoisting

When working in a Next.js project are you required to import react from react in your component files?

No, it's automatically imported, same as modern React projects.

When Node.js is installed does it become the default environment for the system command terminal (not reffering to the VS Code terminal)?

No. But we can enter the node REPL from any terminal via the `node` command. Or you can run a specific Node.js script using the node command followed by the path to the script file." npm (Node Package Manager) commands are not the same thing as Node and out run outside the Node REPL ChatGPT - No. "However, when you install Node.js, it adds its executable file paths to the system's PATH environment variable, which allows you to run Node.js and npm commands from any command prompt or terminal window. If you want to use Node.js in a particular terminal window or session, you can launch the terminal inside your project folder and type node to start the Node.js REPL (Read-Eval-Print Loop), or you can run a specific Node.js script using the node command followed by the path to the script file."

Does getStaticProps have access to the incoming request (such as query parameters or HTTP headers)?

No. If you need access to the request for your page, consider using Middleware in addition to getStaticProps.

What is `fs`? What is path?

Node modules that provide functions for working with files and directories and are useful in Next.js apps. `fs` stands for "file system". It allows you to read and write files, create and delete directories, and perform other file system operations. //The fs module is not available in a browser environment, so it can only be used in Node.js applications. `path` provides utilities for working with file and directory paths. //It can be used in both server-side and client-side code. //.join is one method that can be called on `path`

What does Next.js use to run the server-side code and provide access to the file system and network resources? (what is it built on)

Node.js

When a wrapper component is added to the suite of tests for another component (unit test) does that make it an integration test instead of unit testing?

Not really because a wrapper doesn't contain enough logic to have its own unit test. Maybe if the wrapper contained it's own state logic we would do integration testing instead of unit testing. //Not sure what the functional difference between the two is or if there even is one outside of concept/use-case. I asked ChatGPT and it doesn't seem like there's a functional difference when writing the code

How do you implement lazy loading for a file?

Old version bellow dynamic import as arg for lazy() saved to a const which is in turn wrapped in Suspense Ex: const BlogPage = lazy(() => import('./RouterToBlogPage')); createBrowserRouter etc etc element: <Suspense><BlogPage/></Suspense> //Don't create a regular import entry because regular import entries will "load the file eagerly". //New version wasn't covered in course and I don't understand the doc for the React Router lazy() func.

On what level does Next.js allow you to change between static generation and server-side rendering?

On a page by page basis. Most of the pages will likely be statically generated (this is the default) while the ones that we specify will use server-side rendering at the times/frequency that we specify. //Static generation is preferred when possible because it's faster (built once and served by CDN) but obviously can't be used for dynamic data hints the word "static"

When does the server-side rendering form of pre-rendering generate the HTML?

On each request

What does react performance optimization entail?

Only re-rendering the components that change

What can be used to statically generate pages with dynamic routes in Next.js?

Original answer getStaticPaths New answer A combo of getStaticProps, getStaticPaths, fs methods, matter() from gray-matter, path(), .md files (some other source of data to populate aka hydrate aka statically generate the page with) [] when naming page file .map, .replace, reg ex -- to map over the array that's returned from some fs method being called on the dir containing the .md files so that the new array doesn't contain the .md extension which would otherwaise break the getStaticProps func

Maybe look further into this when I actually care about styling. What is the gist of PostCSS in relation to Next.js? Can reference Next.js official site tutorial under the styling tips section of the metadata section. This section also covers the use of Sass. Probably makes more sense to learn this while also learning Tailwind

Out of the box, with no configuration, Next.js compiles CSS using PostCSS. To customize PostCSS config, you can create a top-level file called postcss.config.js. This is useful if you're using libraries like Tailwind CSS. It's kind of like a translator for modern CSS libraries and frameworks to run in browser that may not yet have support for the modern code.

How can we defer loading? What is the idea behind defer loading?

Outsource the would-be contents of a loader into a separate function. And instead use the defer() function imported from react-router-dom which accepts an obj as an arg where the keys are whatever you want and the values are the names of blocks of loader logic. The idea is to render different promises (components) on a single page at different times so if you know one portion of data is going to take a long time to load, you can render the other portion while you're waiting.

In layman's terms what is authentication? What are approaches to implementing authentication?

Permission for client-side to access protected resources based on credentials. Could use server-side sessions or authentication tokens.

What the first step after install to implement React-Router?

Pick a router. In our case we picked createBrowserRouter() import {createBrowserRouter} from 'react-router-dom'; Expects array of objs as arg createBrowserRouter([ {path: "partOfURLAfterDomainName", element: <ComponentTag />}, {path: "/products", element: <Products />}, {} ]) Sidenote / = default/root path Sidenote II The element key can point to any JSX code such as a <p></p>. It doesn't have to be a component but it usually is.

What benefit does using a dynamic param have over using regular state for determining the general display of a page in the case of sibling routes?

Potentially saves the user some clicks. It's arguably simpler cleaner code and it adds some additional order/structure to the app Enables the use of different links/urls to access different views of the same page so could save the user some nav steps. Whereas React state/dynamic page views are triggered by user interaction via the UI rather than clicking an external URL.

What are two benefits of code-splitting?

Quick initial load of homepage (decreased TTFB). Error thrown on one page doesn't break the rest of the app. Quote This ensures that the homepage loads quickly even if you have hundreds of pages. Only loading the code for the page you request also means that pages become isolated. If a certain page throws an error, the rest of the application would still work.

Where does Await expect to be rendered? What is one approach we could take to display a loading indicator while we're waiting for the promise sent to Await from defer to resolve?

Quote from docs "<Await> expects to be rendered inside of a <React.Suspense> or <React.SuspenseList> parent to enable the fallback UI." We could use the Suspense `fallback` prop to determine what to render while waiting for the promise to resolve. Ex: <Suspense fallback={<p>Loading...</p>}> //Of course we could specify a component or some other UI display as the fallback. It doesn't have to be a <p> //Each Await block is wrapped in it's own Suspense //You typically use SuspenseList by wrapping a set of Suspense components that each correspond to a lazy-loaded component, like this:

What are the three possible values for the state property of the object returned from calling useNavigation()? What do they indicate? What is one thing they can be used for?

Quote from docs navigation.state idle - There is no navigation pending. submitting - A route action is being called due to a form submission using POST, PUT, PATCH, or DELETE loading - The loaders for the next routes are being called to render the next page Normal navigations and GET form submissions transition through these states: idle → loading → idle Form submissions with POST, PUT, PATCH, or DELETE transition through these states: idle → submitting → loading → idle Sidenote could be useful for rendering a loading page when using a loader because our old method won't work in this case. Sidenote Other properties include navigation.location; navigation.formData; navigation.formAction; navigation.formMethod; but we didn't cover these in the course yet.

How can we navigate programmatically on the client-side with Next.js?

Quote from docs router.push Handles client-side transitions, this method is useful for cases where next/link is not enough. Ex: import {useRouter} from 'next/router'; const router = useRouter(); router.push(url, as, options); //url can be a URL object or string of the path you want to navigate to. Views the path as relative rather than absolute //The second arg `as` is an optional decorator and allows you to display a different url on the screen than what's actually being used. Expects URL obj or string. //options - Optional object with the following configuration options:scroll - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to true shallow: Update the path of the current page without rerunning getStaticProps, getServerSideProps or getInitialProps. Defaults to false locale - Optional string, indicates locale of the new page // uses-cases from docs Navigating to pages/about.js, which is a predefined route: Navigating pages/post/[pid].js, which is a dynamic route: Redirecting the user to pages/login.js, useful for pages behind authentication: //Sidenote This is the same hook that we used earlier with the .query method to work with params

What is a better way to accomplish the task on the previous card?

Rather than building your own wrapper component use what react has by default. Fragments 1 ) Import react fragment and use that component rather than building your own wrapper component import React {Fragment} from 'react'; <Fragment></Fragment> Or 2) <React.Fragment></React.Fragment> Or if the app is configured a specific way you can use a short cut without any additional import 3) <></>

How can you lump multiple state slices from the same component into a single state without erasing the other slices every time a single slice is updated? There are two ways to do this, although one is technically incorrect because it fails in niche circumstances. This answer will discuss the improper way.

Rather than passing a single value into the useState() function, you pass an object. The object contains a property for each would be separate state. You also pass an object, rather than a single value, into the setFuncs (functions that trigger a change in state)). The first property in the object should be the spread operator used on the original state. The second property is an overwrite of the specific property that you'd like to update. Ex: const [userInput, setUserInput] = useState({ enteredTitle: '', enteredDate: '', enteredAmount: '' }); const titleChangeHandler = event => { setUserInput({ ...userInput, enteredTitle: event.target.value }); };

What should we do to the data returned in the functions that we point to in the defer() func?

Rather than returning the data directly, use .json() because the defer function doesn't resolve to a Response obj behind the scenes. Ex: const resData = await response.json(); return resData.blabla Not to be confused with return json(data). json() is a utility that can be imported from react-router-dom and has the opposite effect of .json(). the first converts from json to a js obj and the other convert from js to json.

What would we use in place of <form> when working with actions and loaders in react browser? Why?

Rather than using the form element we would use the Form component imported from react-router-dom. The Form component sends the formData to the loader or action rather than the server (as a side effect we aren't automatically redirected to another page).

What are utility folders used for?

Re-usable code that can be used across different parts of the application. Ex: Helper funcs, config files, middleware, validators, logging functions, encryption, file handling, network communication.

What is one handy tool for debugging React apps?

React Dev Tools browser extensions

What are two things you could use instead of a state management library, passing props manually, or using context?

React Router (useLoaderData and useRouteLoaderData). You could use a custom hook because if a component uses a custom hook and the custom hook uses the useState hook, the component will be re-rendered when the state specified in the custom hook changes. Section 25 pretty much creates a simplified version of Redux from scratch using a custom hook. The following is part of that logic but I'm not finishing my notes on it because it seems unlikely that I'd use it and if I need it I can always refer back to this section and the files in GitHub. Stop writing the following notes on video 391 //The following variables are created outside of the custom hook so that they aren't recreated every time the hook is called. In other words if we wrote it inside the hook each component that used it would create it's own instance of the data rather than sharing data. let blaGlobalState = {//data/state that you want to share} let blablaListeners = [//functions that can be called to update all components that are using the hook] let blablablaActions = {} //custom hook below const bleStore = () => { const bleSetState = useState(blaGlobalState)[1]; const dispatch = actionIdentifier => { const newState = blablablaActions[actionIdentifier](blaGlobalState); blaGlloabalState = {...blaGlobalState, ...newState} }; useEffect(() => { blablaListeners.push(bleSetState); return () => { listeners.filter(li => li !== bleSetState) } }, [bleSetState]); } //setState won't ever change (within the confines of a single component) because it's derived from useState and thus react memorizes it across renders. But we add it as a dependency because the thing that checks for errors isn't sophisticate enough to realize this. I think part of the confusion is that he isn't using the `listeners` array to actually do anything in this lecture. So far he just created the array and set up logic to add and remove elements to the array. The elements that are added and removed are unique from one component to the next because they are derived from each component's unique instance/reference of the setState func/obj. It's unique between components because it's defined inside the hook rather than outside like the `listeners` array). Because it's a unique reference for each component, we can use it to add each component to the listeners array. Once the component is unmounted its unique instance of the setState func won't exist anymore because it was defined inside the hook. But it still exist in the `listeners` array because the array was defined outside the hook. This is why we added the cleanup function to the useEffect. We told the `listeners` array to remove that component's UID (derived from it's unique instance of `setState`) when the component was unmounted and thus no longer had the setState instance that we used to create the UID in the array. understanding object references in memory and that function are technically objects may help you understand what's going on better

Why are React Router and Express.js often used together?

React Router for the client-side routing and Express for backend/server-side. Typically neither would be used in a Next.js App because next.js offers it's own routing system.

In React Router. what is one thing that can be used to read and modify the query string in the URL for the current location? What is its syntax?

React Router's useSearchParams hook const [searchParams, setSearchParams] = useSearchParams() // Calling searchParams returns an obj that can be used to access the active route's current search params' values. // Calling setSearchParams returns a func that can be used to change the values of params. It accepts an object of key value pairs. Example of setSearchParams // The serialize function here would be responsible for creating an object of { key: value } pairs from the fields in the form that make up the query. let params = serializeFormQuery(event.target); setSearchParams(params); // The setSearchParams function works like navigate, but only for the search portion of the URL. Also note that the second arg to setSearchParams is the same type as the second arg to navigate.

What are four React libraries that provide animation capabilities? I'll look into one of these if I feel like it closer to employment.

React Transition Group, React Motion, and React Move are all React libraries that provide animation capabilities. React Router Transition is one specifically designed for animations navigations (route transitions) //Section 24 covers some of React Transition Group s well as regular CSS animations and transitions being applied to React

Where can react hooks be used? Where shouldn't they be used?

React hooks can be used in the top level blocks of a component and within react hooks. They shouldn't be used in nested functions, loops, or conditional blocks.

Video 100

React only allows 1 root level JSX element to be returned. This is why we use a div to wrap any JSX elements that we want to be displayed adjacently. The problem with this workaround is that it renders JSX elements such as the wrapping div to the end user even though it doesn't have a functional purpose for the end user. Rendering these extra JSX elements has the potential to slow down the application and complicate the styling process.

What does .createPortal do? What is the method called on? What is it commonly used for? why?

React portals provide a way to render a component's children into a different part of the DOM, outside of the component's parent tree. it's a react-dom method. So import reactDOM from 'react-dom'; enables ReactDOM.createPortal() Often used to render modals (overlay content) to the DOM in a way that's easier for people using screen readers to understand.

What does forwardRef() do?

React.forwardRef is a higher-order component (HOC) in React that allows you to pass a ref to a child component (The component you wrap it around). By default, a components DOM node is private. Sidenote - It can also be used to pass a ref to a useImperativeHandle() hook

React Vid 165 Recap of React behind the scenes, its purpose, how it increases performance optimization

React.js registers the difference between state snapshots in the virtual dom, react-dom renders the difference in the state snapshots rather than the entire component. react comes with another library called react-dom. React is responsible for the virtual dom which is less expensive than manipulating the real dom. React is responsible for tracking props context and state of those components for changes. When it registers that there is a real change AKA a change that should be represented in the real dom it informs react - dom and react - dom is responsible for translating that message into an actual dom rendering. In conclusion react is responsible for re-evaluating components based on state, context and props using virtual dom whereas react - dom is responsible for rendering updates to the actual DOM. It's less expensive to work in a virtual DOM than a real dom

What is .memo? What does it do?

React.memo is a Higher Order Component (HOC) that creates and stores an object in memory. The obj contains all the props that are passed to it. When a parent is re-rendered .memo will compare the new props with the old ones and only re-render if they change (shallow comparison). If you want to use a deep comparison to be more specific by working with objects, array, functions to determine render occurence rather than just numbers, strings, booleans -- you can add a custom comparison function as the second arg to React.memo(). You could also useCallback() as a workaround because it saves objects including funcs and arrays across renders rather than creating a new one and thus changing the reference even if the content is the same. .memo creates more work on virtual side due to memorization and evaluation of memory (stored obj) but less work on DOM side due to less renders so can be used to increase efficiency when component has many children and the parent re-renders frequently without changing the desired UI of the descendants.

What is a path called when you leave off the leading "/". How does this affect children paths and paths specified in Link components?

Relative path. Route definitions don't have to include the CDN. Specifying a relative path in a Link will append it to the currently active route path and .. will go back to the parent route definition.

Question to ChatGPT So the store is used to access state from the initialState objects created in the createSlice entries from one central location. And the `actions` object is used to pass data to, or trigger, the action creators contained in the reducer property of a specified createSlice entry? While the all state is brought together in one central location, the store -- actions are not. Is the purpose of ths devision performance optimization because some files need access to the states while other need access to the action creators, and other may need access to both and we don't want to import more data to any given file than we need to?

Response from ChatGTP Yes, you're correct. The store created using configureStore() provides a central location to access the global state of your application. The actions object generated by each createSlice() function provides a convenient way to dispatch actions defined in the reducer function associated with that slice. The separation of the state and action creators is not just a performance optimization but also a design pattern that helps to organize and maintain the code. It promotes the separation of concerns and makes it easier to reason about the behavior of different parts of the application. It also allows for better modularity, making it easier to add or remove features without affecting other parts of the code.

What is the meaning of `params.someId` from within a loader?

Route params are parsed from dynamic segments of your route definitions (indicated with `:`) and passed to your loader in the `params` obj which can be destructured and used to reference the current value for the specified dynamic param. This is useful for figuring out which resource to load. These params are accessed through the param obj

How would you use previous state as part of the updating function for a new state when working with class-based components in comparison with functional components? use examples for toggling a boolean state slice

Same as functional component except return an object containing the state slice that you'd like to update so rather than setState((prevState) => !prevState) you would type this.setState((prevState) => { return { showUsers: !prevState.showUsers} }) Or leave off the return keyword and wrap the single object literal or expression in parentheses rather than curly braces. this.setState((prevState) => ({ showUsers: !prevState.showUsers })); //However, if the function body contains multiple statements or expressions, then you'll need to use curly braces and an explicit return statement to return a value. //The feature of using parentheses to implicitly return a value is specific to arrow functions in JavaScript.

What are 3 advantages of using local markdown files?

Short Separation presentation and content Colaboration Versioning Long Advantages include - separation of presentation and content so easier to manage and update - Collaboration using platforms such as Git so multiple people can work on the same file at one time - Versioning also using tools like Git to rolback to prebvious content if necessary Overall, using local markdown files is a popular approach for managing content in web development, especially for static sites and blogs.

How can we use Jest to mock fetch?

Short windows.fetch = jest.fn(); windows.fetch.mockResolvedValue({json: async () => [{id: 'p1', title: 'First post"}]}); Long To create a mock function we can use jest.fn() Bellow we use jest.fn() to override the fetch function in our test file. Ex: From within test() function above render... windows.fetch = jest.fn() //Now we can call special methods on windows.fetch such as windows.fetch.mockResolvedValueOnce(Value you want the fetch function to resolve to once it's called) We want to set it to resolve to something that looks like what it would resolve to in production. fetch returns an object that we can call the .json method on for example and json returns a promise so for example if we're expecting an end result of an array of objects that have id properties and title properties Ex: windows.fetch = jest.fn(); windows.fetch.mockResolvedValue({json: async () => [{id: 'p1', title: 'First post"}]}); //If trying to use jest.mock with Axios rather than fetch() see bellow.. import { render, screen } from "@testing-library/react"; import Async from "./Async"; import axios from "axios"; describe("Async component", () => { test("renders post if request succeeds", async () => { // First step: arrange axios.get = jest.fn(); const mockResponse = [{ id: "p1", title: "first post" }]; axios.get.mockResolvedValueOnce({ data: mockResponse }); render(<Async />); // Second step: act // ...nothing // Third step: assert const listItemElements = await screen.findAllByRole("listitem"); expect(listItemElements).not.toHaveLength(0); }); });

How are react portals implemented?

Short explanation Add element with id to html file. Import react-dom. Add component use-case as first arg of reactDOM.createPortal(), specify port id with second arg. Long explanation create a port in the Public/index.html file Ex: <div id="backdrop-root"></div> Import react-dom into the component file Ex: import ReactDOM from 'react-dom'; use the ReactDOM.createPortal() on the component that you want ported to another location. Ex: {ReactDOM.createPortal(<Backdrop onConfirm={props.onConfirm} />, document.getElementById('backdrop-root'))}

Implement useReducer() and explain the various aspects of it's syntax

Simply put... Const import {useReducer} from 'react'; reducerFn = (state, action) => { if(action.type === 'BLA_BLA') { consle.log(data) } } Const [state, dispatchAction] = useReducer(reducerFn, defaultState, defaultFn) submitHandler = (event) => { event.preventDefault(); dispatchAction({type: BLA_BLA, data: event.target.value}) } Sidenote the reducerFn can be written outside of the component block of code. For another example and written explanation of code, scroll down. Syntax 1) import {useReducer} from 'react'; 2) const defaultState = () => { items: [], amount: 0 } 3) const cartReducer = (state, action) => { return defaultState; }; Sidenote - more logic will be added to 3) after we send info to it via the action argument from the dispatchAction func 4) const [state, dispatchAction] = useReducer(cartReducer, defaultState, defaultFn); 5) const addItemHandler = (item) => { dispatchAction({type: 'ADD', item: item }) }; Explanation 1) hooks need to be imported from the react library before use 2) We assigned third argument of our reducer function, the default state, to a variable because it's cleaner 3) We created a reducer function with a default value. Notice how the hook isn't used yet. The first argument is the latest state snapshot, the second argument is the action to be performed when dispatchAction is called. 4) We used the useReducer hook. We destructured the array containing two elements that the hook returns by default. The first element in the array is the most recent state snapshot. The second element in the array is the dispatchAction, the function used to send info to and trigger the action of the second argument in the specified reducer. To the right of the = we specify which reduced function we want to use, a default state, and possibly a default function. We created a function and linked it to an onClick prop for a button. WE also send it the item prop to access the item whose button was clicked. Inside the function we call dispatchAction to pass an object to the action. These dispatch objects commonly contain a type property to indicate what is being sent, as well as the content from the item that we would like the useReducer function to have access to. Sidenote - notice 'ADD' is all caps and a string while item is a variable taken from the item associated with the item whose button was clicked. On the next card we'll use the object that was passed from the dispatch to the cartReducer function (through the action argument) to write logic for changing the state.

What is something that you might useContext for rather than Redux? What might you want to use Redux for rather than useContext? Why?

Something like authentication or theme that isn't updated frequently. Updating a cart. useContext isn't optimized for high frequency. Any time a component uses context it is re-rendered anytime any of the properties in the context obj change rather than just when the property that is cares about changes.

What is an action creator?

Something that creates an action (often an object) with type property and often a payload to be sent to a reducer. In the context of this course we can create custom action creators with a Thunk. React Toolkit creates some for us by default based on the reducer contained in createSlice entries. We call them to dispatch actions to the slice const dispatch = useDispatch() disptach(thunkName(data)) or dispatch(sliceName.actions.specificReducerInCreateSliceEntry{bla: bla})); or without passing a payload dispatch(sliceName.actions.specificReducerInCreateSliceEntry));

When might you want to use context (list 4)?

State used by many components, not expected to change frequently, connecting components don't need would-be prop, simple/small app Sidenote - Redux could be used for high frequency more complex cases because useContext() isn't optimized for it.

What are the two forms of pre-rendering?

Static Generation and Server-side Rendering

What kind of host do we need for a React SPA considering a React SPA is a static website meaning it doesn't contain any code that must be executed on the server. It only consist of HTML, CSS, and JS files and maybe couple of images. It's all executed by the browser on the client.

Static Site Host. We don't have to pick a host that offers server execution. Sidenote - we could create a full-stack react app rather than SPA in which case we may need a different host.

What is it known as when a page is statically pre-rendered with data? What is the result of statically pre-rendering without data called?

Statically pre-rendering with data is typically referred to as pre-rendering with hydrated HTML or populated HTML. Skeleton of shell HTML

Section 22 Deploying React Apps

Test First test the code by using all of it's functionality to find potential errors. Optimize Look for potential improvement. Maybe implement lazy loading. If you change something measure the performance before and after to see what effect it had Build - npm run build run the build script to minify the app so that it runs faster and takes less space on servers and computers. There's some functionality that's useful for dev mode but not needed for production mode so this is removed by running the build script. Stuff like JSX is also transformed because the browsers don't know how to read JSX. The JSX is also transformed when we work with the code on a development server (known as life transformation). The content of the build folder is what will be uploaded to the server Upload to Server choose a service provider and plan to upload you app/website to servers configure the server environment

What should we keep in mind when rendering a Link component

The "page" that contains them (typically above Outlet) should be added to the createBrowserRouter() function so that they're eventually rendered in the RouterProvider component via the `router` prop.

What does the Component prop mentioned in the previous card hold?

The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page. Quote from docs Next.js uses the App component to initialize pages. You can override it and control the page initialization and: Persist layouts between page changes Keeping state when navigating pages Inject additional data into pages Add global CSS To override the default App, create the file ./pages/_app.js as shown below: export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page.

What are two similarities that actions and loaders have? Kind of a dumb question because they have more than two similarities.

The Form component is used to trigger one or the other based on the specified method and sends the `meta` object from which the request and params objects can be destructered.

What are 3 of the main perks of using the Image component from next.js rather than the default html from the last card?

The Image component automatically handles stuff that you would otherwise have to implement manually to optimize the image. Stuff like... 1) Ensuring your image is responsive on different screen sizes. For example changes size based on screen size so we don't have to use CSS media queries 2) Optimizing your images for example avoids shipping large images to devices with a smaller viewport. Accepts modern image formats like WebP 3) Only loading images when they enter the viewport (aka lazy loads the image). Images load as they are scrolled into viewport. And more //Images are always rendered in such a way as to avoid Cumulative Layout Shift (CLS) to improve SEO.

Why is it more efficient to use a wrapper than a div to display adjacent top-level JSX elements?

The Wrapper component is not rendered to the Dom and does not slow down the application so the requirement of 1 root JSX element is met without slowing down the application.

Skip this question and maybe separate it into multiple questions at some point. What are the differences between a query param and a dynamic param when using react router?

The beginning of a query param in the URL is indicated with a `?` whereas a dynamic param look just like the rest of the URL (just proceeded with a `/`). Query portion Ex: ?valueAssignedToNameProp=currentValueOfUserInput&etc... Query params are added to the URL via the name prop of an input element of a Form whereas dynamic path segment are enabled via a `:` in the route definition (path property in react router). A URL, including the current query param value and or current value for a dynamic segment of the route can be accessed from a loader via `request.url`. An object containing all the query params can be accessed via the `useSearchParams` hook or to access a specific query param use request.parameters.paramName. useSearchParams can also be used to manipulate (read and write rather than just read) the query params. An object containing all the dynamic route values can by accessed via the `useParams` hook. Query params are used to pass information to a server or different section of the website via the URL whereas the value of a dynamic route segment is used to determine what data to display a particular page with.

When does a cleanup function run?

The cleanup function is executed when the effect is unmounted, or when the effect is re-run with different values in the dependency array

When should I use getStaticProps? List 4 things

The data is available at build time The data comes from a headless CMS such as local filesystem containing .md files Need to increase the speed of the page for SEO The data isn't private or user specific (can make exception to this) //When I say data I mean the results of the getStaticProps function that we pass to the component as a prop. However, as getStaticProps function itself runs only on the server-side, it will never run on the client-side. It won't even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers. This means that instead of fetching an API route from getStaticProps (that itself fetches data from an external source), you can write the server-side code directly in getStaticProps.

What is an alternative to the useContext() hook?

The default .Consumer component that react adds to the context object

.... is a top-level React component that wraps all the pages in your application.

The default export of the _app.js file

What does the test function from Jest expect as args?

The description of the text (string) that you make up to identify the test in the testing output. And an anonymous (not named) function that contains the actual testing code Ex: test('bl bla', () => { The function uses the render func imported from the testing library which accepts the component you want to test as the arg Ex: render(<App />); Then we get ahold of some element from the simulated browser by using the screen func which is also imported from the react testing library Ex: const linkElement = screen.getByText(/Text that's rendered inside the element to identify it/i) //The above passed a reg ex as the arg that looks for the specified text in a case insensitive way. Then we check to see if an element containing that text is in the document. Ex: expect(linkElement).toBeInTheDocument() //So now we can run the test script from within the terminal and the test will fail if the element is not found and it will succeed if the element is found Ex: npm test //Entering the above in the terminal will return a list of options. Option `a` will run all the `test()` functions from the the files appended with `.tests.js`. For some `npm test` without adding any options will run them all by default. //The terminal will return some results of the test //After it's run for the first time it will automatically monitor the code and return new results if changes are made.

Whats the meaning of fs.readFileSync(fullPath, 'utf8');

The fs.readFileSync() function is a Node.js file system method that reads the entire content of a file synchronously and returns the data in the specified encoding format. The fullPath argument is the path to the file to be read and utf8 specifies the encoding format. In this case, the function is being used to read the content of a Markdown file in the fullPath location and returns the data as a string in UTF-8 format. //Maybe look further into encoding formats further down the road

What are 4 props that the object returned from calling getStaticProps might contain?

The getStaticProps function should return an object containing either props, redirect, or notFound followed by an optional revalidate property.

What should we keep in mind when specifying the width and height props of the Image component?

The height and width props should be the desired rendering size, with an aspect ratio identical to the source image.

How can we use React Router to update the state of the token app-wide?

The loader responsible for saving the token to a variable will be the loader associated with the homepage (RootLayout page) which is where the user is redirected upon login and logout. Is the token isn't there then the variable will be undefined. Old Answer If there's a single RootLayout component we can add to its path def a loader that creates a variable for the storage space where the token would be. The variable would be equal to the token value if the token was currently there and equal to undefined if the token wasn't there. Write logic for login and logout to add/remove the token and redirect users to the home page (RootLayout component) to trigger the loader and thus update the value returned from it. That variable returned by the loader will now stay up-to-date and can be used to render the UI dynamically. Add the id prop to the root path def to access the value in other components via useRouteLoaderData('idName') ChatGPT In React Router v6.8.2, when a navigation occurs, React Router will not re-evaluate all elements in the component tree. Instead, it will selectively update the parts of the tree that need to be updated based on the new location. React Router uses a technique called declarative routing to define routes in a declarative way using JSX. When a user navigates to a new URL, React Router updates the URL in the browser's address bar and then uses the new URL to determine which components should be rendered. React Router will compare the new location to the previous location and update only the parts of the tree that have changed.re-evaluation based on navigations. In React Router v6.8.2, when a navigation occurs, React Router will not re-evaluate all elements in the component tree. Instead, it will selectively update the parts of the tree that need to be updated based on the new location. React Router uses a technique called declarative routing to define routes in a declarative way using JSX. When a user navigates to a new URL, React Router updates the URL in the browser's address bar and then uses the new URL to determine which components should be rendered. React Router will compare the new location to the previous location and update only the parts of the tree that have changed.

Static site generation aka static rendering and server-side rendering are both forms of pre-rendering. What are the main differences between them?

The main difference is when the HTML is generated. Static rendering generates the HTML at build time, while server-side rendering generates the HTML dynamically on the server at request time or during build. static pre-rendering is faster and more efficient than server-side rendering, but it is limited to static pages that don't require dynamic data. Server-side rendering is more flexible and can handle dynamic data, but it is slower and more resource-intensive. Next.js supports both static pre-rendering and server-side rendering out-of-the-box, and developers can choose which technique to use depending on the specific needs of their application.

What is the relationship between Form, data from an input field in the Form, the name prop, FormData, and request.formData?

The name prop can be added to Form fields to access their value from loaders and actions by using request.formData.get(specifiedName). React Router derives formData from the FormData obj that the browser automatically creates when a Form component sends data to an action. Elaboration ChatGPT ? So when Form send data to the action, the browser constructs a FormData object automatically and we can access this form data with request.formData in the action or loader? A Yes, that's correct. When the Form component sends data to the action, the browser automatically constructs a FormData object that contains the form data. In the action or loader function, you can access this FormData object using the formData property of the request object that is passed as an argument to the function. You can then extract the form data and use it to make a request to your server or API. ?2 To enable access of an input field of a Form through request.formData in an action or loader does the input filed need a name prop? A2 Yes, to access the value of an input field in a FormData object via request.formData in an action or loader, the input field needs to have a name attribute. The name attribute specifies the name of the input field, which will be used as the key in the FormData object to store the corresponding value.

What should we add to a Form's inputs to reference them in the action or loader?

The name prop. Quote from docs "Make sure your inputs have names or else the FormData will not include that field's value."

Explain `notFound` in the getStaticProps object?

The notFound boolean allows the page to return a 404 status and 404 Page. With notFound: true, the page will return a 404 even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author

Explain Error Boundaries. What method indicated an error boundary? How are Error Boundary files typically named? What do Error Boundaries return?

The only use case for class-based components in modern react. Class-based wrapper used to catch errors thrown by wrappies. Uses the componentDidCatch() class-based component lifecycle method. Returns this.props.children (this is what makes it a wrapper). File names for error boundaries are typically variations of ErrorBoundary.js such as BlablaErrorBoundary.js Sidenote I think we're supposed to use `throw new Error(blabla)` from the child components because catches won't be caught by the ErrorBoundary but I should verify this.

What does the pageProps prop mentioned in the previous card hold? I'll revise this card when I know more

The props for the currently active page. Quote from docs pageProps is an object with the initial props that were preloaded for your page by one of our data fetching methods, otherwise it's an empty object.

What should be the shape of the `redirect` object that's used in getStaticProps?

The redirect object allows redirecting to internal or external resources. It should match the shape of { destination: 'string', permanent: boolean } Ex: redirect: { destination: '/', permanent: false } // If the redirects are known at build-time, they should be added in next.config.js instead

How can you have a relative path in a Link reference the proceeding path segment rather than the parent route?

The relative="path" prop. Sidenote The default would be relative="route"

What do we typically return in a react-router-dom action function?

The results of a special react-router-dom function called `redirect`. //"It's recommended to use redirect in loaders and actions rather than useNavigate in your components when the redirect is in response to data." - docs

With the exception of the index.js file in the "path" folder, what is the filename used for when working with Next.js?

The route name (aka path name aka url name). domain-name.com/filename would access the particular page file. The index.js page would be accessed with just domain-name.com/ If you had nested folders, each folder could have it's own index.js file that would be displayed for the path the uses the folder-name rather than "index". domain-name.com/foldername

Is a page component statically generated even is you don't use getStaticProps?

The shell for the page will be statically generated meaning the html won't be populated aka hydrated with data from any external sources

What is Client-side Rendering? What's the idea behind it?

The strategy used if the data doesn't need to be pre-rendered. Server-side rendering increases TTFB so if it's not need -- Client-Side Rendering will increase SEO. Used for stuff like private, user-specific pages where SEO in not relevant.

What prop could you use as an alternative to className in the previous card?

The style prop could be used to write inline styles

What is an alternative for storeName.dispatch() when using react-redux rather than just vanilla redux?

The useDispatch hook Ex: import {useDispatch} from 'react-redux'; const dispatch = useDispatch(); const decrementHandler = () => { dispatch({type: 'decrement'}) }; <button onClick={decrementHandler}> Decrement </ button>

What hook is used to handle errors thrown from within a loader?

The useRouteError hook is used to handle errors thrown from a loader.

Revised question - What are two ways to access query params from within a loader or action? Old question - How can you add user input from a Form to the URL and then use that URL in a loader to make a request?

The useSearchParams hook from React Router or request.url to access the full url rather than just the query params In the Form component's input element add the name="q" prop. In the loader `let url = new URL(request.url)` and then use `url` for the fetch. //When you add the name='q' prop to an input element in a form from React Router, you are setting the name of the input field to "q". This name corresponds to the name of the query parameter that will be added to the URL when the form is submitted. //Sidnote maybe if you just wanted to access the param and not the entire url you could destructure `params` from `meta` which is sent to the loader or you could useSearchParams. Sidenote - maybe make separate card for this tangent URL is an obj in the browser environment. Browser environment refers to the the runtime environment provided by web browsers to execute JS code. Browser runtime environments include various APIs (fetch for example) and features that allow JS to interact with the browser and it's surrounding environment such as the DOM and XHR. The main browsers share the same core feature and APIs but have some differences. The browser environment is different from other JavaScript environments, such as the Node.js environment, which is designed to run JavaScript on the server-side.

Consider this -- we write logic where the absence of an auth token prevents submission of a form and modifies the UI to remove the link that would navigate a user to the form to begin with. What are we missing?

The user could still manually type in the URL to view the form

Where does the userEvent object come from? What is it used for?

The userEvent object is imported from the @testing-library/user-event library. This library is an extension to the React Testing Library and provides a set of utility functions that simulate user interactions with the DOM. Used for the second A (Act).

Where is a loader implemented?

The variable it's saved to is added as a prop to route definitions. But we typically write the logic in the file whose component needs the data. Or in it's own file if the returned value is needed in multiple places.

How can hooks be identified in react?

They all start with the word "use". useState() is a common

In addition to metadata such as <title> what is usually added to the <Head>

Third Party JavaScript (script for stuff like analytics, ads, and customer support widgets) via the Script component imported from next/script

What does useActionData do? What is it commonly used for?

This hook provides the returned value from the previous navigation's action result, or undefined if there was no submission. The most common use-case for this hook is form validation errors. If the form isn't right, you can return the errors and let the user try again: It's like the same things as useLoaderData except for actions. The returned value is automatically parsed by react-router-dom because it's a fetches return Response objs.

What is TTFB?

Time To First Bite - the time that it takes for a user's browser to receive the first byte of page content. SEO metric

What should we keep in mind about class-based components in relation to their access to props?

To access props and to enable the class-based component in general we need to 1) import {Component} from 'react'; 2) specify the component class is extending from the component import.. class ComponentName extends Component { } 3) Use this.props to access props rather than just props

What is the purpose of a useEffect() hook? What is it's syntax variations? What is the difference in outcome between the variations? What are some things it might be used for?

To increase efficiency by separating the re-rendering of a portion of code from that of the component that it is found in. useEffect(someFunc, [dependancy]) - runs after dependency change useEffect(someFunc, []) - runs after initial render of component useEffect(someFunc) - runs after every render on component Side Effect - Not directly involved in triggering the UI change. Things like HTTP request, intervals, timers, and local storage. Sidenote The array dependencies should include the variables that are used by the 1st arg except for state updating functions (setBlaBla and reducers) and built in browser API functions (like setTimeout), and variables defined outside of component.

What is the purpose of Redux Devtools?

To troubleshot by conveniently viewing the overall state of you redux store. It provides insights into the redux store, into the action history, and much more. If you click on one of the actions that's been triggered it will provide information about that action such as the unique identifier, payload, how the state looks afterwards, diff between previous state and current state. You can click jump on an older action and the UI will change to reflect what it looked like before all the consecutive actions. You can use skip to go step by step through the actions Sidenote It works out of the box if you're using redux toolkit. If you don't have redux toolkit installed you have to write some extra code to get redux devtools working properly Sidenote II @@INIT is an initial first action that is dispatched behind the scenes to set you initial store state.

Is a React app more likely to use server-side authentication or token-based authentication? Why

Token-based authentication because a session ID can only be verified by the server that issues it and is used to access session instances (state) stored on the server but React SPA contain much of the state on the client-side so it makes more sense to use a token which can be stored on the client. // Token-based authentication is a form of stateless authentication // Token-based authentication: In token-based authentication, the server generates a token after the user has successfully authenticated, which is then sent to the client and stored locally (usually in a cookie or localStorage). This works better for react because all the state is stored on the client to avoid http request. Server-side auth stores session (instances of the app) for each user on the server to be accessed with session id by client. // In server-side authentication, the server generates a session for each authenticated user, and stores the session information on the server. The server then associates each subsequent request with the appropriate session, based on a session ID that is sent by the client. This means that the server needs to maintain state between requests, which can be difficult to manage in a distributed, stateless architecture like a React application.

What does the .json() method do when called on the response object?

Translates the json into a JS object

Where is the test function imported from?

Trick question, it's globally available after installing Jest so it doesn't need to be imported

What technology does Next 13 add to increase performance optimization such as automatic font optimization, improved image loading, and more efficient code splitting?

Turbo pack

What tools/technologies and setup are used for testing code?

Typically a testing framework for running the tests and asserting the results (determining whether the run was a success or a fail). Jest is typically used for this especially in React apps. & We also need a library to simulate (render) the app for the tests to interact with it. React Testing Library is commonly used for React apps. Jest and React Testing Library both come as part of the create-react-app install but I've seen videos saying not to used create-react-app via the setupTest.js file in the source folding (imports jest dom) and the AppTest.js file (imports from react testing library as well as some cookie-cutter code). App.test.js has the purpose of testing the App component. It's common practice to name the test files after the component's that they're used to test and they're appended with .test.js.

What are the three main categories of automated tests? Describe them.

Unit tests - smallest chunks that you want tested like individual functions or components in isolation. Integration test - the combination of two or more building blocks End-to-End (e2e) tests - Test for entire workflows like a practical user experience such as logging in, browsing the store, adding items to the cart, and checking out.

Explain the following code const cartReducer = (state, action) => { if (action.type === 'ADD') { const updatedItems = state.items.concat(action.item); const updatedTotalAmount = state.totalAmount + action.item.price * action.item.amount; return { items: updatedItems, totalAmount: updatedTotalAmount }; } else if (action.type === 'REMOVE') { const updatedItems = state.items.remove(action.item); const updatedTotalAmount = state.totalAmount - action.item.price * action.item.amount; return { items: updatedItems, totalAmount: updatedTotalAmount, }; } else return defaultCartState; };

Upadated answer II We created a reducer function to update the state object properties. The way which we updated the object was determined by the 'type' property of the action object. Updated answere We implemented useReducer to update the state of an object. One of the properties of the object that we updated was an array of "items", another property was totalAmount. The reducerFn expected an object from the dispatchFn with a "type" property and used an if statement to decide what to do with the object based on the type. To update the state of the first object, the dispatchFn object contained properties for item, price, and amount. We used JavaScript logic on these property to update the items, and total amount properties of the object whose state we wanted to update. In short we wrote part of the logic necessary to update a cart of items and their associated prices. Original Answer Bellow We update the state using the action.type, determined by the use case of dispatchAction, to tell the reducer func what to do in these conditionals. We use the concat method rather than push because it returns a new array whereas push modifies the original which is important because we like state to be imutable.

Why wouldn't we fetch data or perform some other async operation whose results we want pre-rendered by next.js from within a useEffect hook?

Updated answer The function in useEffect runs after the first render but server-side rendering loads data before the first render. Original answer The function contained in a useEffect is executed after the component is executed and rendered for the first time. So if we useEffect for this scenario the async data is only available on the second render but next.js uses the first render to determine what should be pre-rendered on the server.

How do you make a file from the pages folder in a next.js accessible through a dynamic param like in cases where the same page is used and loaded with varying data depending on what the path segment is currently equal to?

Use [] around the file name Ex: [paramId].js Or around the nested folder name that uses an index.js file [folderName] -> index.js

Probably best to skip and re-write this question at the end of the current Next.js tutorial section so I can tie it all together when it makes more sense.. After the code in the previous card has been written how can we implement getStaticProps by using the dynamic path we created?

Use given `id` to fetch necessary data to pre-render dynamic route. 1) in the same file that we created the getAllPostIds func -- we also create a func that we'll call getPostData and pass the `id` to it as an arg. Ex: export function getPostData(id) { const fullPath = path.join(postsDirectory, `${id}.md`); const fileContents = fs.readFileSync(fullPath, 'utf8'); const matterResult = matter(fileContents); return { id, ...matterResult.data, }; } 2) Replace import { getAllPostIds } from '../../lib/posts'; with import { getAllPostIds, getPostData } from '../../lib/posts'; export async function getStaticProps({ params }) { const postData = getPostData(params.id); return { props: { postData, }, }; } // The post page is now using the getPostData function in getStaticProps to get the post data and return it as props. Now, can update the Post component to use postData via the postData prop that it now has access to // https://nextjs.org/learn/basics/dynamic-routes/implement-getstaticprops has links to view the code all together. Can use as cookie cutter to implement static generation of dynamic routes in Next.js. We statically generated of pages using dynamic routes

What are two things you want to do with an authentication token after it is stored?

Use it to access protected resources and change display of UI Original answer below... send it along with future http request that will need it to access various backend resources. Also set an expiration on it to remove it from storage and logged the user out after a period of inactive time.

How do you create a suite?

Use the describe() function. Similarly to test(), describe(), is a globally available Jest function.

How can we access a dynamic param using Next.js after we've named the file with the proper syntax for it to be dynamic? More than one approach but describe the built in hook approach

Use the query method on the router object that's returned from the useRouter hook imported from next/router Ex; import {useRouter} from 'next/router'; const router = useRouter(); const {paramId} = router.query or router.query.paramId Sidenote - The same router object is returned from useRouter and withRouter

Vid 314

Verify - where we got `mode` from. Was it set with : in route def? - that .get() was used to access the amil and password prop - new URL(request.url).searchParams looks weird Using custom component returning Form component from react router to triger an action for that route. action logic - destructure request -> create variable for request.formData - > use the variable (probably along with .get()) to access the email prop (which I think we added to the request.FormData obj by adding the name prop to one of the inputs in the Form component) -> Same for password prop -> check current query param to determine what to do with this info (send request to create new account or to login for example). Can't use hook inside action logic to access the current query param so instead we use built-in browser functionality Ex; const searchParams = new URL(request.url).searchParams; const mode = searchParams.get('mode') || 'WhatYouWantTheDefaultParamToBeInCaseThereIsn'tACurrentValue; -> const response = await fetch entry that uses the current param to determine what portion of the backend to send the password and email to, set the method to POST, add JSON.stringify(desiredData) to the meta-data body prop, meta-data will depend on how the backend is set up -> backend will now perform necessary logic to create new account or sign in -> as a side note we could check to insure `mode` (current param value) matches an acceptable path on the backend before sending the request. Ex: if (mode !== login || mode !== signup) {throw json({message: 'unsuported mode'}, {status: 422})} Or Rather than throwing an error we could just set it to the default value -> check the status prop and `ok` prop on the response returned from the fetch to decide what to display next on the client-side -> if the response is fine do something with auth token -> use redirect import to change pages -> don't forget to add the action to the route definition //Common to name the action function `action` but to change the name to be more specific when importing to the App file to be added a route def under the action prop Ex: import {bla as blabla} from '../bleh' Sidenote - when creating an account you should verify that the email they're trying to use isn't already associated with an account. Next Video useActionData to display messages on form in case the Auth didn't go through.

What two things should we keep in mind when adding the value portion of a prop in defer({})? How could we specify for the defer to wait on a particular value before rendering any of the other values?

We call the functions (values) rather than just point as them, so funcName() not funcName You could add the `await` keyword directly before a value if you want react router to wait for that particular promise (value) to be resolved before rendering any of the page (overarching page). Side using `await` would pretty much void the fallback prop in the Suspense associated with this particular promise but add the fallback anyway because an error will be thrown if you don't.

How can you avoid the default behavior described in the previous card?

We can use the "end" prop. The end prop specifies that isActive should only be true if the paths are an exact match rather than just matching the first part. <NavLink to="/" className={({isActive}) => (isActive ? someCSSClass : undefined)} end>

How might we inform users that something is loading?

We could create a state with a default value - false set to true at beginning of function which contains fetch function set to false at end of function that contains fetch function In the JSX, use && along with the current state to determine what is returned

How do we make the store aware of the reducers in the previous card?

We import configureStore from redux toolkit. Use it instead of createStore. Example of 1 slice - const store = configureStore({ reducer: counterSlice.reducer // Or variable representing nameOfCreateSlice }) Example of > 1 slice - const store = configureStore({ reducer: {counter: counterSlice.reducer, secondReference: secondSliceName.reducer} }) //The property keys: `counter` and `slice` could be named anything but it's common to give them the same name as the stateSlice that they'd be used to access. Sidenote We use `reducers` (plural) inside createSlice() and we use `reducer` (singular) in configureStore(). createSlice entries automatically merge the reducers contained within them and configureStore automatically merges the reducers passed to it from the various createSlices entries. So you end up with one reducer. Sidenote II If we were using vanilla redux rather than redux toolkit and wanted to add more than one createSlice reducer to the store we would use a feature called combineReducers.

Where do we typical write the logic for these actions and loaders and where do we implement them?

We write the logic in the associated component, import it, and use the import in the route definition. Side They run in the browser so we have access to stuff like local storage and cookies.

What does Next use for bundling and optimizing the client-side code?

Webpack

Explain state scheduling

When setState is called the state isn't necessarily update immediately from the perspective of the computer even if it seems immediate from human perspective. Instead the state update is scheduled in the order that it was executed. When a state update depends on the previous state we use the following format for this very reason. setBla((prevBla) => !prevBla) this avoids using the same state snapshot for two separate state updates in a scenario where the state update is called twice before the 1st update is implemented.

If the Link component is used when does next.js fetch the code for a linked page?

When the Link to a page is visible in the browser viewport. So by the time you click the link, the code for the destination page will already be loaded in the background, and the page transition will be near-instant!

When might we use Redux rather than just sticking with context?

When the application is large/complex Redux can avoid what would otherwise be a complex context or many nested contexts. It can also increase performance in scenarios where the component involved experiences high frequency changes.

What are fetchers good for?

When you want to work with data involving a loader or action without triggering a route/view change (navigation). Useful when you need to... quotes from docs "Many interactions with the server aren't navigation events. This hook lets you plug your UI into your actions and loaders without navigating." "fetch data not associated with UI routes (popovers, dynamic forms, etc.) submit data to actions without navigating (shared components like a newsletter sign ups)" etc... Optimistic UI - consider two components on a single page. You want some user interaction with one of the components to trigger a UI change in both components as soonas the interaction occurs rather than waiting for something like the form submission. A fetcher enables this.

Side Tangent - Some Agile certifications cover technical practices such as test-driven development, continuous integration, and automated testing. What is test driven developement? What is CI? What is Jest? What is Docker? What is Kerbernetes?

Where the dev writes the test before the code that needs to be tested. dev regularly adds their code to the central repository where automated builds and tests are run the catch any integration issues early. Jest is testing framework that can be used to automate the testing and deployment. Docker is a containerization platform that allows developers to package their applications and dependencies into a portable container. Kubernetes automates the deployment, scaling, and management of containerized applications across a cluster of nodes //Often used in Agile dev. but some teams test after the code is writing. Writing the test before supposed to force the dev to think carefully about writing quality modular code that meets customer expectations. ChatGPT Test-driven development (TDD): TDD is a software development practice where developers write automated tests for their code before they write the code itself. The idea is to use tests to drive the development process, by defining the desired behavior of the code before it's written. The process typically involves writing a failing test, writing the code to make the test pass, and then refactoring the code to make it more maintainable and efficient.

What is an alternative to using the method discussed in the previous card?

Write custom action creators in the form of Thunks. Usual contained in their own files possibly in a folder called actions. Helps keep the slices and components files' lean.

What is automated testing? Why does it exist?

Writing and running code that tests the code of your application both on the individual block level and as a whole. Saves you the trouble of manually checking every time you make a change to the code. Instead you can just run the test and it will provide information about any bugs and help avoid operator error during testing. \\It exist as an addition to manually testing, not a replacement

In redux what does Fat Component refer to in relation to reducer functions staying pure?

Writing async and effects logic related to updating state (dispatching) inside a useEffect entry contained in the component file. Because we can't write async logic like fetch directly in the reducers contained in the create slice entry in a slice file -- one place we could write it is in a useEffect in the component file and then dispatch the results to the reducers to work their magic and update the store.

What is YAML?

YAML is a human-readable data serialization format that is often used for configuration files, data exchange between programming languages, and other applications where data needs to be stored or transmitted in a structured format. In the context of gray-matter, YAML is one of the supported formats for front matter. It is used to define key-value pairs that describe the metadata of a Markdown file. // Data serialization is the process of converting data objects or structures into a format that can be easily stored, transmitted, or shared over a network. This is typically done by converting the data into a standardized format such as JSON, XML, or YAML, which can be easily read and interpreted by other systems or applications. The serialized data can then be transmitted over a network or stored in a file, and later deserialized, or converted back to its original format when needed. Data serialization is a fundamental concept in modern computer programming, as it allows different systems and applications to communicate and exchange data with each other.

Are there circumstances where lumping the state slices of a component together is the optimal choice?

Yes

Does PEMDAS apply to calculations run through the Math object?

Yes

Is it likely that both the component whose ref is being shared, and the component who is receiving the ref would use the `useRef()` hook when `useImperativeHandle()` is involved? Why or Why not?

Yes The child component would combine information from the DOM with local logic, expose it to the parent, and then the parent would need useRef to use what was shared from the imperative handle.

Is it possible to chain multiple .then() to a single fetch?

Yes function makeHttpRequest() { fetch('https://example.com/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); }

Is it common to use the previously listed syntax for a ternary expression in react JSX?

Yes because it is easier to read than the other

Can useDispatch() functions be added to the dependencies array of useEffect?

Yes, I guess react-redux saves it with useCallback behind the scenes so it never changes and doesn't effect the execution of the useEffect func

Does react enable you to use JSX Code as the value associated with variables That came before the returned JSX snippet?

Yes, you can use this feature to keep the primary returned JSX snippet lean and clean. This pretty much enables you to move JSX and associated logic out of the returned portion of the JSX and into the standard logic portion and then add the variable that you assigned it to to the returned portion.

How can you load the various parts of a page separately?

You can defer loading meaning we tell react-router that we want to start rendering a page as soon as a specified portion of that page has it's promise resolved rather than waiting on the promises from the rest of the page to also resolve.

Can you use hooks inside of loaders?

You can not use hooks inside of loaders. Hooks can only be used in react components or hooks and loaders are not written inside of components.

fetch uses GET by default. How can you specify a post?

You can pass an object as a second argument. In that object you can set the "method" key to a POST value. You also need to specify what you want to post using the "body" key. Body accepts JSON data, not js objects. So we convert any js object that we want posted to JSON by using a built in js func called JSON.stringify() some API also require you to modify the header field value to 'Content-Type': 'application/json' Ex: fetch(https://someUrl, { method: 'POST' body: JSON.stringify(movie) header: {'Content-Type': 'application/json'} })

Other than adding global styles what can the App component be used for?

You can use this component to keep state when navigating between pages

What should we keep in mind in reference to the chain related to lifting up a state?

You cannot skip links in the chain, for example you cannot send data directly from a grandchild to a grandparent without first sending it to the parent. Side Note - Context and libraries may contradict this statement. What is React context? React context allows us to pass down and use (consume) data in whatever component we need in our React app without using props. In other words, React context allows us to share data (state) across our components more easily.

What are two different ways of accessing the information related to a specific input to determine validity? When might you use one over the other?

You could useRef with ref or you could use an on onChange with state. useRef is tyically used if you want to manipulate the element somehow whereas onCHange just tracks the changes

What should we keep in mind when defining a route definition's path as absolute?

You have to include the common domain name in each route definition. In other words when writing an absolute path definition you have to write the full path rather than just the part that you want to append to the parent.

What needs to be done before you can utilize useReducer?

You need to import it just like you would with useState

What is fetch?

a JavaScript method use to interact with APIs.

What does the fetch method accept as arguments?

a URL string and optionally an object with properties to manipulate the data package such as header, body, method

What is the FormData object? What is it commonly used for?

a built-in JavaScript object that is used to represent data that is sent in the body of an HTTP request when submitting a form. It is commonly used in client-side JavaScript to gather form data and send it to a server for processing.

How can you tell react-router which page (custom component) to load if an error occurs on a particular page or it's children?

add the errorElement property to the route object for the page whose error you want to handle //ErrorPage is a custom component const router = createBrowserRouter([ {path: "/", element: <RootLayout/>, errorElement: <ErrorPage/>, children: [ {index: true, element: <ComponentTag />}, {path: "/products", element: <Products/>}, {path: "/cart", element: <Cart/>} ]} ]); When a route definition does not have an errorElement, errors will bubble up through parent routes until the find one. By default only the root route has the ability to throw error but we can change that, with a loader prop for example.

What is .focus

an DOM input method that places the cursor in the input.

What is <title>

an HTML tag that specifies the title of a document. It is typically included in the head section of an HTML document, and is used by web browsers to display a title for the page in the browser tab <Head> <title>First Post</title> </Head> //Both the Head component and the title tag are important for optimizing the SEO

Provide an example of an async function saving the fetch GET response to a variable.

async function fetchMovieHandler() { const response = await fetch('https://blabla') } )

What is an alternative to chaining multiple .then()? What is a primary consideration for it's use?

async functions work similarly to .then. Allows you to save the responses with const which helps avoid what's known as callback hell. They also handle errors differently.

Where can I find all the slides for the React course on Udemy?

at the end of each module

Video 176

axios is a package that makes it easier to deal with API requests and responses. Rather than using a package like axios we can use the fetch method which is a JavaScript feature that's built into the browser. fetch('https://desiredURL', optional second argument such as JS object where we configure various options such as extra http header, body, method etc..) fetch uses the get method by default

In the future explain the following line from the context of being found in a class-based component. Take a deep dive on prototypes, the this keyword, and bind. <button onClick={this.whateverMethod.bind(this)}></button>

bind - a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with. prototype - In JavaScript, every object has a hidden property called [[Prototype]] (sometimes referred to as "dunder proto") which refers to another object. This object is known as the prototype of the object. this - In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

Consider adding the before mentioned param to a fetch. How would you do so?

bla = params.bla fetch('someURL' + bla)

.blebl

blabl

Blabla

blba

Bl

ble

blabla

bleble

What are 4 things useSWR handles?

caching, revalidation, focus tracking, re-fetching on interval and more // ChatGPT When useSWR revalidates, it checks if the time elapsed since the last successful fetch is greater than the specified revalidate interval. If the elapsed time is less than the interval, useSWR returns the cached data. Otherwise, useSWR revalidates by fetching new data from the server and updating the cache. In contrast, when useSWR re-fetches, it always retrieves the latest data from the server, regardless of whether the cached data is still considered fresh. Focus-tracking on interval is a technique used by useSWR to determine when to start revalidating the data. It works by tracking whether the browser window is currently focused or not, and only initiating a revalidation when the window becomes focused. Additionally, useSWR can be configured to revalidate on a regular interval, regardless of focus, to ensure the cached data stays fresh.

componentWillUnmount()

called before class-based component unmountings (removal from DOM/UI). This includes umounting due to rerender. Essential the cleanup function called after useEffect()

componentDidUpdate()

called when state of class-based component changes. essential use effect with some dependencies. Receives two arguments -- prevProps and prevState.

What words should be kept in mind when working with class-based comonents?

class extends super constructor this.props render this.state this.setState componentDidMount componentWillUnmount componentDidUpdate componentDidCatch this.methodName.bind(this.stateObj) throw new Error contextType

How is state implemented in class-based components?

class Users extends Component { constructor() { super(); this.state = { blbl: true, blabla: 'Test' }; } } Important Sidenote this.state always has to be set equal to an object. It can't be set to a boolean, string, number, etc All state slices would be placed in a single object.

Is PureComponent used for functional components or class-based?

class-based

What's a typical lifecycle for a token? How might the presence or absence of an auth token effect the UI and navigational capabilities of a website? Other than removing the token, what should we do when a user logs out? What logic might we write for logout?

client sends credentials -> server creates and sends auth token to client -> client stores auth token and send it with future http request for access to protected backend stuff -> token deleted/expires based on something like a timeout or logouts UI appearance such as login link and logout button changes based on presence of auth token. When a user logs out we typically redirect them to the home page. We would create an action for logout that uses the `redirect()` func from react router. Because logout doesn't have it's own page we can leave off the element prop in it's route def in createBrowserRouter. Could could wrap the logout button by `Form` and associated `action` prop and method of `POST` (bc actions aren't triggered by GET).

What makes an error boundary?

componentDidCatch() called above super, constructor, this.state often the class=based component is named some variation of ErrorBoundary The following method will be deprecated so instead we should use static getDerivedStateFromError(error) The componentDidCatch method has a prop called error passed to it by default. error can be used to reference aspects of the error that was thrown by the child component.

Do we use const, var, or let with useState entries?

const

Use the syntax and comment lines to describe a common approach to providing the context object?

const ContextName = React.createContext({key: valuePairsForDefaultValuesOfWhatYouWantToShare}) export const CustomProviderComponent = (props) => { //All related state logic return (<ContextName.Provider value={{keys2BUsedByOtherComponents2Access: valuesCreatedInThisCompoent}}> { props.children } </ContextName.Provider>) //The keys in this value obj should be the same as the keys in context obj and the associated values are the states you want to share from the custom component } export default ContextName; //Now CustomerProviderComponent can be wrapped around any other component and that component and its descendants will be able to access the contents of the Context obj by using useContext or the .Consume component.

What is the useReducer() syntax?

const [state, dispatchFn] = useReducer(reducerFn, initialState, optionalInitialFn)

How can you access a state-slice value if the state-slice is an object and you're using redux toolkit to create the store and using react-redux to access it?

const counter = useSelector((state) => state.identifierSpecifiedInConfirgureStoreEntry.specificValueFromInitialStateObj) //useSelector can be used for any value, not just redux state and that's why we pass an arrow function specifying state. State is a reference that's automatically assigned to the object containing all the state-slices added to our configureStore entry. Ex: import useSelector from 'react-redux'; const counter = useSelector((state) => state.counter.counter); The first .counter is a key you created for a reducer in the configureStore entry. The second .counter is a key in the initialCounterState obj found bellow. const initialCounterState = {counter: 0, showCounter: false}; const counterSlice = createSlice({ name: counterSlice, initialState: initialCounterState, reducers: { increment (state) {state.counter++}, increase (state, action) {state.counter + action.amount} } }); const store = configureStore({reducer: { counter: counterSlice.reducer, otherReference: otherSlice.reducer})

useImperativeHandle() with useRef and forwardRef() Ex: from Input.js component file

const import React, {useRef, useImperativeHandle} from 'react'; const Input = React.forwardRef( (props, ref) => { const inputRef = useRef(); const blabla = () => { inputRef.current.focus(); }; useImperativeHandle(ref, () => { { pointerTo: externalValueSuchAsblablaFoundAbove, pointerTo2: ExternalValue2, Etc... } }) }) return ( <input ref={inputRef} )

What does the strategy prop of the Script component do? What does assigning it a value of lazyOnload do?

controls when the script is loaded strategy="lazyOnload" A value of lazyOnload tells Next.js to load this particular script lazily during browser idle time

What must be done before a component can be used in another file?

create export and import entries export default ComponentName; import ComponentName from 'filePath' Sidenote If you export as a named func rather than default -- the import will need to wrap the name in curly braces

createSlice() - Last time I got the syntax of last portion wrong

createSlice() - obj as arg. obj contains name property, a nested obj for initialState, another nested object for the reducers property in which we can write code that appears to directly mutate the state (converts behind the scenes so we're not actually directly mutating the state obj). The properties have to be named thus. Ex: const intialState = {counter: 0, showCounter: true}; const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment(state) {state.counter++;}, decrement(state) {state.counter--;}, increase(state, action) {state.counter + action.amount} toggleCounter(state) {state.showCounter = !state.showCounter;} } })

What are some key features that Redux Toolkit has that regular redux and react-redux don't? List two key functions and 5 key methods called between the two functions.

createSlice(), .actions, .reducer configureStore(), .dispatch, .subscribe, .getState Explained createSlice() - contains one or more slices. each slice contains properties -- name: bla, initialStateObj, reducers: {{actionCreator1}, {actionCreator2}, {actionCreator3}} .reducer - nameOfCreateSlice.reducer - refers to the reducer that react toolkit creates behind the scenes by combining all the reducers contained within the createSlice entry into a single reducer. .actions - nameOfCreateSlice.actions - references the actions object that redux toolkit automatically creates for us behind the scenes. The actions object contains all the action creators that we made in the reducers property of each slice contained in the createSlice entry configureStore() - use in place of createStore. Accepts an object with a reducers property where we specify which createSlice variable we'd like to include in the store as well as optional properties -- middleware, devtools, preloadedState, enhancers, etc... etc... nameOfConfigureStore.subscribe(listener) nameOfConfigureStore.dispatch - or we could use react-redux useDispatch hook nameOfConfigureStore.getState() - or we could use react-redux useSelector hook

How does creating, providing, and using context differ between class-based and function-based components?

creating still uses the React.createContext() method. Providing still uses the ObjectName.Provider component. Class-based components don't have access to hooks so we can't use useContext() but we can still use the ObjectName.Consume component. You can listen to a context by adding the following above the constructor function. static contextType = ContextObjectName; once that entry is made you can use this.context.users in the places where you need access to the users.

What are two properties contained in the obj returned from calling matter()? what are their associated values?

data: An object that contains the metadata in the front matter of the Markdown file. content: A string that contains the Markdown content of the file.

How does using defer change the type of func the loader is?

defer() isn't asynchronous it just point at async code. So the loader doesn't need to be an async function now but of course the logic that you outsourced still needs to be.

How can you access the input data from a change event handler?

event.target.value example on card 60 and in ExpensesForm.js

What does useSelector() expect as an argument? What does it automatically do behind the scenes?

expects a function as an argument. The function should pass the state and return the part of the state you want to use in this particular component. Ex: const counter = useSelector(state => state.someSlice.someValue); Sidenote useSelector automatically subscribes the component to the store so you don't need to make a separate entry. It also automatically clears the subscription for you when the component is unmounted (performance optimization).

What are four things that can be used to have getStaticProps run at times other than build?

fallback props, revalidate prop, revalidate() func, Incremental Static Regeneration Quote from docs getStaticProps always runs during next build getStaticProps runs in the background when using fallback: true getStaticProps is called before initial render when using fallback: blocking getStaticProps runs in the background when using revalidate getStaticProps runs on-demand in the background when using revalidate() When combined with Incremental Static Regeneration, getStaticProps will run in the background while the stale page is being revalidated, and the fresh page served to the browser. Notes from video Have it return `revalidate: 10` //10 is just an example and is the number of seconds between each revalidation of the data that this particular getStaticProps function is passing as props to the component in the file where it's contained. //

What is the result of returning `fallback: true` within getStaticPaths

fallback version of page will be served on first request -> in background requested page will be statically generated and served for subsequent requests

What should we keep in mind about fetch in relation to status code error's effects on catch (error) {}

fetch doesn't throw status code error to catch (error) {}. Instead is a has a property on the response object with key "ok" which is set to true or false based on the status code. You can use this Boolean in an if statement to throw an error of your own. Ex: try { blabla if (!reposnse.ok) { throw new Error('Something went wrong') } } catch (error) { setError(error.message) } Sidenote now you can use && to display something to the user indicating that there is an error. Ex: {!isLoading && error <p>{error}</p>} Or better yet use the axios package which, by default, throws an error to catch when a status code error occurs.

How can we access the .json() response data using fetch and .then

fetch('https://someUrl').then(response => { return response.json().then(data => { data.results }) })

What is often chained to fetch() and why?

fetch().then().catch .then() to specify what to do when the request receives a response .catch to handle any errors

What is the difference between fetcher.Form and Form?

fetcher.Form doesn't trigger a navigation

What is the purpose of fetcher.load? What is the difference between fetcher.data and useLoaderData?

fetcher.load() loads data from a route loader that otherwise wouldn't be loaded until something like the route was navigated to or the route Link was visible in the browser. useLoaderData() - After route actions are called, the data will be revalidated automatically and return the latest result from your loader. fetcher.data - Once the data is set, it persists on the fetcher even through reloads and resubmissions. //More on useLoaderData -Note that useLoaderData does not initiate a fetch. It simply reads the result of a fetch React Router manages internally, so you don't need to worry about it refetching when it re-renders for reasons outside of routing. This also means data returned is stable between renders, so you can safely pass it to dependency arrays in React hooks like useEffect. It only changes when the loader is called again after actions or certain navigations. In these cases the identity will change (even if the values don't).

What is the difference between fetcher.submit and fetcher.Form? And what is the difference between fetcher.submit and useSubmit?

fetcher.submit is the imperative version of <fetcher.Form>. If a user interaction should initiate the fetch, you should use <fetcher.Form>. But if you, the programmer are initiating the fetch (not in response to a user clicking a button, etc.), then use this function. useSubmit is the imperative version of <Form> that lets you, the programmer, submit a form instead of the user. fetcher.submit is the imperative version of fetcher.Form so it stands to reason that the difference is just that one triggers a navigation event and the other doesn't. But the example in the official docs says they're both used to programaticaly used to log the user out so IDK. I posted a question about it on Discord

What might decrease the amount of time between a user clicking a button and the display being changed?

fetching the data ahead of time and just use onClick to render what has already been returned. You can fetch on render and dependency change with useEffect()

write a React.forwardRef() implementation that forwards the ref to a parent component

from Input.js... import React from 'react'; const Input = React.createRef((props, ref) => { return (<input ref={ref} />) }) From file using <Input />.... import {useRef} from 'react'; const amountInputRef = useRef(); return (<Input ref={amountInputRef} />) Now ` amountInputRef.current.blabla` can be use to access and manipulate all the values associated with the current state of the input element in the DOM.

What are two fs functions that are relevant to Next.js and what do they do?

fs.readdirSync - It takes a directory path as its first argument and returns an array of file and subdirectory names in the directory. fs.readFileSync - Synchronously reads the entire contents of a file into a string.

What are three types of functions that are called on screen? What is the main difference between them?

get, find, and query. get function throw an error if an element isn't found immediately. find functions return a promise and wait for it to be resolved for a specified amount of time of a default of 1 second. query functions don't do either. Returns `null` if the element isn't found.

What can be used to import static external data into an index page?

getStaticProps

Where can getStaticProps be used?

getStaticProps can only be exported from a page. You cannot export it from non-page files, _app, _document, or _error. Also, you must use export getStaticProps as a standalone function — it will not work if you add getStaticProps as a property of the page component. //write it in top level of the file rather than in the component

What is grey-matter? What does matter() do?

gray-matter is a library that offers a function called `matter()` which can extract YAML front matter such as title, author, and date from .md (Markdown) files and return it as a JavaScript object that can be used in your code. //

What attribute does the Link component from Next.js expect?

href='/blba/ble'

What are the 3 possible values for fetcher.state? What hook is it similar to and how is it different? What is one possible use-case?

idle, submitting, loading, navigation.state is different because it only works if a navigation occurs providing a visual indicator of the current stage of the process in the UI such as `loading...` idle - nothing is being fetched. submitting - A route action is being called due to a fetcher submission using POST, PUT, PATCH, or DELETE loading - The fetcher is calling a loader (from a fetcher.load) or is being revalidated after a separate submission or useRevalidator call

Where is the image component imported from?

import Image from 'next/image';

How are refs implemented? What do they do? why?

import React, {useState, useRef} from 'react'; const blabla = useRef(); console.log(blabla.current.somePropertyOrMethod); <input ref={blabla}></input> Now blabla.current.desiredProperty now has direct access to the input element found in the DOM. This access can be used to view or even manipulate the input's data. Sidenote "current" is an object that useRef creates by default. It contains many properties such as "value". Sidenote using this makes the component an "uncontrolled component", meaning it access the DOM direct rather than running through React for every little thing.

Provider tag syntax

import entry <ContextName.Provider value={}> Sidenote - Provider is a component that's automatically assigned to context objects. Typically value is passed an object so it would be value={{}}

What is import html from 'remark-html';

import html from 'remark-html' is a way to import the remark-html package in a JavaScript module. The remark-html package is a plugin for the remark processor that converts Markdown to HTML. By importing the html function from remark-html, you can use it as a plugin in your remark processing pipeline to convert the Markdown content into HTML.

How do you provide the context?

import its file, wrap the component you want to have access to the context object with <ContectObjectName.Provider></ ContextObjectName.Provider>

How can you create a CSS styles wrapper?

import styles from './layout.module.css'; export default function Layout({ children }) { return <div className={styles.container}>{children}</div>; } use Layout as wrapper wherever you desire

How and when might you implement imperative routing?

import useNavigate from 'react-router-dom'; const blabla = useNavigate() //The following would be triggered based on something like an onSubmit or timeout blabla("/products")

Client-side declarative transitions between routes can be enabled via the ________ component exported by next/____.

import {Link} from 'next/link'; //This link component doesn't send an http request like default html approach would. Unless it's clicked as an external URL (meaning the SPA hasn't even been visited yet), in this case would obviously send an http request and the data would be pre-rendered on the server.

What is one way to create links for the URLs defined in our createBrowserRouter func?

import {Link} from 'react-router-dom'; <Link to="products">Products Page</Link> Side typically we're going to have a navbar in the header so we would place that Link component in <header> <nav> <ul> <li><Link to"/products">Products Page</Link></li> </ul> </nav> </header> Side Behind the scenes the Link component works with anchor tags (<a><a/>) not link tags (<link></link>). Side We don't use default html anchor tags directly because that would send a new request to the server which would defeat the entire purpose of an SPA. So we wouldn't use <a href="/products">Products Page</a>

How can a component wrapped by a Provider access specific values from the context object?

import {useContext} from 'react'; import CartContext from '../../store/cart-context'; const ctx = useContext(CartContext); sidenote - pass the object itself rather than the custom provider component ctx.DesiredPropertyKey; Sometimes the Consumer component is used instead.

How can we dispatch actions to a createSlice entry using redux toolkit and react-redux?

import {useDispatch} from react-redux; const dispatch = useDispatch(); dispatch(nameOfCreateSlice.actions.nameOfActionCreator(someFormOfData)) or dispatch(importName.nameOfActionCreator(5)) or dispatch(importName.nameOfActionCreator({bla: blabla, ble: bleble})) The above would trigger the action from the reducers: section of specified createSlice (nameOfCreateSlice in this example) that matches whatever you put in place of nameOfActionCreator. But typically we'll export the actions object as a named export from the createSlice file and then use dispatch(importName.nameOfActionCreator). This way we're only importing the part of the specified createSlice file that we need. Ex: export const counterActions = nameOfSlice.actions import {counterActions} from 'blabla'; We may do something similar for nameOfSlice.reducer to import it to the store file because the store file doesn't need the actions object same as the components don't need the reducer object. Rather than just triggering one of the actions you can also pass a payload to it which is what many of the actions expect. The payload is often an object but it doesn't have to be. It can also be a primitive value such as a number Ex: dispatch(importName.nameOfActionCreator(5)) or dispatch(importName.nameOfActionCreator({bla: blabla, ble: bleble})) Sidenote - obviously don't have to write a type property to the dispatch because its created for us behind the scenes by the actions obj. and referenced by nameOfActionCreator. If we dispatch actual data rather than just triggering an action then the actions obj will also add a `payload: {data: we send}` property to the dispatched object for us behind the scenes. So the dispatched object would look like { type: "nameOfActionCreator" payload: {obj containing all the data we send} }

example of accessing what is shared by the useImperativeHandle, .forwardRef, useRef trio from Login.js file in which I'm using the the Input component that used useRef(), useImperativeHandle(), and React.forwardRef

import {useRef} from 'react' const passwordInputRef = useRef(); <Input ref={passwordInputRef} /> Now passwordInputRef.current.desiredPropertySharedByImperativeHandle can be used

What are two react-redux hooks and a function whose purpose is to utilize what was provided? Briefly differences.

import {useStore, useSelector} from 'react-redux'; useStore generalizes the entire store. useSelector makes it easier to specify a particular slice of state from the store The .connect() func is used for class-based components. (vid 237 has an example)

What is the "index" property associated with createBrowserRouter used for?

index: true can be used in place of path: "" to indicate the child of the layout wrapper that you want to be the default page associated with the path of layout wrapper. For example the path of the layout wrapper is "/" but of course the wrapper is just the wrapper so you have to pic an initial page to render and rather than specifying a relative path like path: "" (which is acceptable), you could use the index property like index: true

In regard to reg ex (regular expressions), what does it mean to anchor the pattern to the end of the string?

indicate that the pattern should match only at the end of the string //In the regular expression /\.md$/, the dollar sign indicates that the pattern should match only if the string ends with .md. If the string contains .md in the middle or at the beginning, the pattern won't match.

In regard to reg ex (regular expressions), what does it mean to escape the dot.

indicate that we want to match a literal dot (.) character rather than any character. In regular expressions, the dot (.) is a special character that matches any character except newline (\n)

In regard to reg ex (regular expressions), what does it mean to delimit the pattern.

indicate the beginning and end of the pattern

What are 3 ways to incorporate CSS in our JSX snippets?

inline - using the 'style' attribute.. Ex style={{cssAttribute: value4Attribute}} - uncommon css classes - className={desiredCssClass} along with .css.module import - common wrapper/card - common to create a component with sole purpose of styling - named Card or Wrapper - determine styles, pass props.children, import to component that you want to style with it, and wrap it's JSX with the Card/Wrapper tags.

What are two benefits of returning a Response rather than throwing an Error in relation to useRouterError?

isRouteErrorResponse returns true if the route error is a response route error (meaning we throw an error using new Response for the error rather than throw new Error) Ex: throw new Response("Bad Request", { status: 400 }); "While you can throw anything and it will be provided back to you through useRouteError, If you throw a Response, React Router will automatically parse the response data before returning it to your components.". So if I'm not mistaken we can remove `JSON.parse` from `message = JSON.parse(error.data).message` at video 293 minute 5 second 13 when extracting info from the error. It will also make future integration with Remix easier. I think there are some other reason too but in short it's what the docs recommend

How is the name of the fetch() method deceiving?

it can also be used to post not just get

what is firebase

it has a lot of services such as databases and APIs. Sidenote - In this course we are not going to use the database, we are going to use the free rest API provided by Google. We can use it to post data to a database of our choice.

What is the .getByRole method called on? What is it?

it's called on the screen object and it's similar to screen.getByText except it allows you specify roles like 'button' rather than strings that are contained in the element.

How are keys implemented?

key={someUUIDofYourChoice} is added as prop to each sibling component as it's being mapped to the list. Ex: {props.items.map(expenses => ( <ExpenseItem key={expense.id} title={expense.title} amount={expense.amount} date={expense.date} /> )};

Do loaders execute in the browser or on the server and what does this imply?

loaders run in the browser so we can access browser functionality such as local storage and cookies inside the loader.

How can we access the authentication token from localStorage?

localStorage.getItem('keyName')

What object contains the request and params objects that are sent to loaders and action?

meta

Describe the utilization of the react-redux Provider component

npm install react-redux import {Provider} from 'react-redux'; import store from './storeFolder/storeFile typically it will be used in the index.js file and be wrapped around the rendered <App /> component so that all descendant (entire app) can access the store. And of course pass the store prop Ex: root.render(<Provider store={store}><App /></Provider>);

Provide an example of implementing redux

npm install redux //or npm install redux react-redux if using it in a react app. Redux isn't react specific that's why I listed the regular npm install entry as well. react-redux makes it easier to subscribe components to the store. const redux = require('redux'); // import redux from 'redux' const store = redux.createStore(counterReducer); //pointed at the reducer func we want to use const counterReducer = (state = {counter: 0}, action) => { if (action.type === increment) {return {counter: state.counter + 1 }}; if (action.type === decrement) {return { counter: state.counter - 1 }}; return state; }; //typical reducer func accepting state with default value and action to determine what to do store.dispatch({type: 'increment'}); store.dispatch({type: 'decrement'}); //would be pointed at by something like an onClick store.subscribe(counterSubscriber) //giving the following func access to the counter state slice that's now in the store. const counterSubscriber = () => { const latestState = store.getState; console.log(latestState); }; //using the getState method to access the current state from the store

Redux Basics

npm install redux react-redux const redux = require('redux') const store = redux.createStore(reducerFn); const reducerFn = (state = {counter: 0}, action) => { if (type = 'increment') {return {counter: state.counter + 1}} } const increment = store.dispatch({type: 'increment', action: 'object'}) const decrement = store.dispatch({type: 'decrement'}) const counterSubscriber = store.subscribe(functionToHaveAccess) functionToHaveAccess = () => { currentState = store.getState(); console.log(currentState) } install -> require -> use .createStore method and pass the deducer function name -> create the reducer function which accepts state and action -> use .dispatch method to send actions to reducer -> use .subscribe(funcToHaveAccess) to provide access to state from the func that you determine.

What could we return in a scenario where all the if statements of a loader fail? Why

null because if loaders just return nothing it will cause an error

What is a built-in event that fires when an input is unfocus?

onBlur

What does the onLoad prop of the Script component do?

onLoad is used to run any JavaScript code immediately after the script has finished loading. onLoad={() => console.log(`script loaded correctly, window.FB has been populated`) }

What is the meaning of path.join(postsDirectory, `${id}.md`);

path.join is a Node.js method that joins all given path segments into one path string. In the expression path.join(postsDirectory, ${id}.md), postsDirectory is a directory path and ${id}.md is a filename. The method concatenates the directory path and filename with the appropriate path separator for the operating system, creating a full path to the Markdown file with the given id.

What is a main difference between actions and loaders?

pre-loading data vs mutating data Long explanation For actions - ""They provide a way for apps to perform data mutations with simple HTML and HTTP semantics while React Router abstracts away the complexity of asynchronous UI and revalidation"" - "Route params are parsed from dynamic segments and passed to your action. This is useful for figuring out which resource to mutate:" - "the action property does not preload data for the next branch of routes.". <React.Suspense> can be used to lazy-load data and render the component only when the data has been loaded." useEffect, Thunks, react-query library, and Redux-Thunk library could also be used for this. For loaders - "Each route can define a "loader" function to provide data to the route element before it renders." - "As the user navigates around the app, the loaders for the next matching branch of routes will be called in parallel and their data made available to components through useLoaderData." - "Route params are parsed from dynamic segments and passed to your loader. This is useful for figuring out which resource to load:

How can you have a variable representing a string be read as a number?

prepend the variable name with +

What does a loader do?

provides data to a route element before it renders instead of render -> fetch -> re-render

What is remark?

remark is a powerful and flexible markdown processor for Node.js and the browser. It can be used to parse markdown files and generate an abstract syntax tree (AST) representing the structure of the markdown document, which can then be transformed with plugins before being converted to other formats.

Explain the parts of the following and what it returns remark() .use(html) .process(matterResult.content);

remark() is a JavaScript function from the remark library that is used for parsing, transforming, and serializing markdown (creates an abstract syntax tree). In the given code, remark() is called with .use(html), which tells remark to use the remark-html plugin to transform the markdown into HTML. Then, .process() is called with matterResult.content, which is the content of a markdown file with YAML front matter that has been parsed using the gray-matter library. The process function will return a Promise that resolves to an object containing the HTML output of the markdown transformation. So, the overall purpose of this code is to parse a markdown file with YAML front matter, transform the markdown into HTML using the remark-html plugin, and return the HTML output. //Without the YAML front Matter

What is remark()

remark() is a function in the remark library, which is a JavaScript utility for processing and transforming Markdown syntax into an abstract syntax tree (AST) format that can be programmatically manipulated or rendered into HTML, React components, or other formats. The remark() function creates a new processor that can apply one or more plugins to modify the Markdown syntax or the AST representation. These plugins can add or remove syntax, transform existing syntax, or inject new data into the AST. The processor can be used to parse Markdown text into an AST, and then convert the AST back into Markdown or another format. Overall, remark() is a powerful tool for working with Markdown syntax in JavaScript applications, particularly for generating static websites, documentation, or other content-driven projects.

What is remark-html?

remark-html is a plugin for remark that converts the AST generated by remark into HTML. By using both remark and remark-html together, you can parse a markdown file into an AST and then convert that AST into HTML.

What is a commonly used obj that's nested in the request obj that's sent from the Form to the loader or action? What is a common method that's called on this obj? What does the method expect as an arge?

request.formData.get(namePropValuefromFormField)

How can we access the method used on a Form from a loader or action?

request.method

In the previous card, what is important to note about the words, response, data, and results.

response and data can be named whatever we want them to be name but they are common naming conventions. They're both being used to access what is automatically passed to .then. results is a key found in the returned json that points at an array of data. The data in the array is similiar to objects with keys to access data by using blabla.bla. Of course what's returned by the JSON is dtermined by the backend programming language.

What do you need to do when you add the pages/_app.js file and when you update the file?

restart the server // Ctrl + c to stop the server -> npm run dev to start the server

What does the .max() method do when called on the Math object? What needs to be done if you pass an array name as it's arg?

returns the highest numeric value that it received as an arg. Use the spread operator Math.max(...arrayName)

Where do you use the value returned from calling createBrowserRouter()?

router prop of RouterProvider component returned in the App component. import {createBrowserRouter, RouterProvider} from 'react-router-dom'; const router = createBrowserRouter([ {path: partOfURLAfterDomainName, element: <ComponentTag />}, {}, {} ]) <RouterProvider router={router} />

What are 3 key features of Next.js?

server-side rendering file-based routing (Next 13 will use directory based) full-stack capabilities - helps with connecting standalone backend code such as reaching out to a data-base. //Image optimization is also a big one Built-in server-side rendering for initial page - Preparing the content of the initial page on the server rather than the client. Can help with search engine optimization because crawlers see what a user would see and rather than loading a skeleton of the initial page and then loading the data which can cause a loading flicker, server-side rendering pre-renders the contents of the initial page in server before sending anything. So it takes longer for the initial view to be rendered but the initial view will be complete/correct rather than a skeleton page and then the page populated with the correct data/contents. //search engine optimization doesn't matter for all pages, only the pages that could be directly accessed from a link in the search engine. So for example it wouldn't matter for a page that could only be viewed after login. //Client-side rendering would still apply for pages other than the initial one. This makes sense considering client-side rendering is like the whole idea behind React. //Next.JS is used to get the best of both worlds when it comes to server-side and client-side rendering. file-based routing - In traditional React you don't even have a router, just the illusion of one. Next.JS can change this with file-based routing. To do this Next.js refers the folder that you name 'pages` and refers to the folder/file structure you set up in the pages folder to determine routes. Pretty much making the route path the file path like we we're doing before React. full-stack capabilities Makes it easy to add our own backend API into our React project using Node.js code. Used for stuff like storing data, getting data, auth, etc

What is meant by keeping a reducer function pure?

side effect free and synchronous. So no fetching for example.

What are three props commonly used by the Script component?

src, strategy, and onLoad

What are 4 props that the Image component accepts that default html image elements also accept?

src, width, height, alt

Explain each part of the reducer function found in the previous card.

state - exactly what is sounds like actionDispatch - triggers state update, performs logic, passes result of logic to reducerFn reducerFn - accepts state and result of dispatch action -> performs its own logic -> returns new state initialState - exactly what you think it is initialFn - optional value used in cases where you want to update initial state based on something like an http request before the user even have time to trigger a state update Side Note - dispatchFn() is typically used to pass an object to reducerFn. this object typically contains a "type" property which varies between each use-case and can be used by the reducerFn to determine what to do with the rest of the object properties. For example, consider a remove button and an add button. You could add an onClick prop to each button and set them equal to two separate handlers. the handlers would each call dispatchFn but one would pass an arguement with type: ADD_USER and the other would pass and object with type: REMOVE_USER. Of course nyou'd pass other stuff such as event.target.value into the same object.

What do people mean by local state, cross-component state, and global state?

state that affects a single component, state that affects multiple components, state that affects the entire app.

What do Markdown files do? What are their files appended with?

store and manage content that can be displayed on a website after easily being translated from markup to HTML via a static site generator such as next.js .md

Where would global css styles typically be placed? Does it have to be named thus?

styles/global.css The above is common naming convention and placement but not necessary

Where might we create CSS component-level styles other than a wrapper to be used by multiple components?

styles/utils.module.css imported as util styles rather than just styles like the Layout

What are some common input types?

text, number, date

How is setState called in a class-based component

this.setState({showUsers: false}) It always takes an object and the object contains the state slices (object properties you want to update). The other state slices remain the same.

What is .toString()

toString is a method in JavaScript used to convert a value to a string. It can be called on any value and returns the string representation of that value. For example, calling .toString() on a number would return the number as a string. In the context of the remark() function with the remark-html plugin, calling .toString() on the processed HTML content converts the HTML content to a string so that it can be used in rendering a web page or in other parts of the application that require a string representation of the HTML.

filename.module.css automatically assigns __________ ______________ for each _______

unique classNames for each use-case (instance) This way you don't have to worry about className collision

Consider an EventForm (custom component created by us) implented in NewEvent and EditEvent (also custom components created by us). The EventForm returns Form (component imported from react-router-dom). The action that this Form triggers needs to have a dynamic fetch method and URL. The `patch` method should be used for the EditForm component. The `post` method should be used when the action starts with the NewEvent component. How can this be accomplished?

use EventForm component instances in EditEvent and NewEvent. Pass method prop from NewEvent and EditEvent Ex: method="post" and method="patch" could destructure the prop rather than using props.method in EventForm. Ex: const EventForm = ({method}) => {} In this scenario EventForm returns and the custom react-router `Form` component to trigger the action and the Form component accepts a method prop to send to the action so we just pass along the method whichever method we recieved from the other components. Ex: <Form method={method}> In the action logic extract the current `method` value by destructuring the `request` obj from the object that's automatically passed to the action from the `Form` component and accessing the method prop which is automatically part of the `request` obj sent from Form which we have set dynamically at this point. Ex: const async function action({request, params}) { method = request.method } Now in the fetch portion of the action logic, set `{method: method}`as the second arg (meta data).

What is difference between the useMemo() hook and the useCallback() hook?

useCallback is used to store custom functions whereas useMemo is used to store the results of expensive computions.

How can you avoid the infinite loop described in the last card?

useCallback() because it saves functions across executions. This way the function (object) doesn't change just because of a re-render, it only changes if the contents change. So we can avoid an infinite loop. Ex: const name = useCallback(async () => {etc etc blabla}, [])

What is the second most important react hook?

useEffect

Gist of useFetcher()

useFetcher can be used to interact with actions and loaders in many ways and the whole idea is to do something with the loaders and actions without a navigation. Some of the methods provide status of loaders and action while others access various pieces of data returned from actions and and loaders while others trigger them.

Where should forwardRef() pass the ref?

useImperativeHandle or a component

What is the syntax for useImperativeHandle()?

useImperativeHandle(ref, () => { { pointerTo: maybeLocalFuncName, pointerTo2: maybeFuncThatusesLocalState, Etc... } }) Sidenote in the above entry, `pointerTo` is what would be used along with `useRef()` by parent components to access the associated value

How can we access the data from a defer loader? What do we do with that data to specify when a component should render?

useLoaderData Await component and it's `resolve` prop Ex: const data = useLoaderData; <Await resolve={data.aKeyNameSpecifiedInLoader}></Await> //Each key in the loader is a promise and by adding it to the resolve prop of Await we specify that we want to the contents of Await to be rendered when that promise is resolved rather than waiting for the rest of the promises on the page to also resolve. //The object returned by useLoaderData is used to access the promises (properties) of the object that we passed as an arg to the defer() func in our loader. //Could also destructure the key and add it to the resolve prop directly (basic js functionailty) Ex: const {keyNameSpecifiedInLoader} = useLoaderData; <Await resolve={keyNameSpecifiedInLoader}

How can the data returned from a loader function be accessed from component files?

useLoaderData or useRouteLoaderData useLoaderData Provides the value returned from loader of nearest route on context (I think this means its own loader or nearest ancestor loader). If the value returned is a response -- useLoaderData automatically extracts the data (first arg) of the Response obj. The loader itself resolves fetch promises to Response objs. Response objs' second arg is an obj containing meta-data such as the status code of the fetch request. useRouteLoaderData Like useLoaderData except lets you choose which loader to use based on the id prop in the route definition. Ex: useRouteLoaderData(valueOfIdKeySetInRouteDefintionAssociatedWithDesiredLoader) The only data available is the routes that are currently rendered. If you ask for data from a route that is not currently rendered, the hook will return undefined. Sidenote these two may also differ in the storage of the values they provide.

What are the key differences between useNavigate() and <NavLink> considering they're both used to trigger a route change?

useNavigate() doesn't render a UI element. It's triggered based on something other than the user clicking a link. Use-cases include of form submissions, a timer expiring, etc.. more of a side effect than NavLink. NavLink renders an <a> (anchor tag) to the UI and accepts props for stuff like styling the link. useNavigate() is an imperative approach whereas <NavLink> is declarative. Sidenote Declarative programming is a programming paradigm that emphasizes the use of a declarative language to describe what should be done, rather than how it should be done. In the context of react-router-dom, this means defining your routes and navigation links using JSX components that describe the structure of your application. Imperative programming, on the other hand, emphasizes the use of statements that directly control the flow of the program and modify the state of the application. In the context of react-router-dom, this might involve manually manipulating the history object or using useNavigate to programmatically navigate to a different page.

What does useRouteError return?

useRouteError returns an object whose shape depends on what we threw whether it be a Response, an Error, or some custom obj.

What is useSubmit() and what does it return? What are some common use-cases?

useSubmit is a hook from React Router, "The imperative version of <Form> that lets you, the programmer, submit a form instead of the user" and it returns a function that accepts two args -- the data you want to submit (or null), and the meta-data (such as method and action). You're not required to use both args if you don't want to. It's a way to programaticaly submit forms. Use cases 1 "Submitting the form every time a value changes inside the form:" Ex: function SearchField() { let submit = useSubmit(); return ( <Form onChange={(event) => { submit(event.currentTarget); }} > Blbal </ Form> 2 "This can also be useful if you'd like to automatically sign someone out of your website after a period of inactivity." but it's more common to use the useNavigate hook in this case. Ex: submit(null, { method: "post", action: "/logout" }) //Could et it to be triggered by period of inactivity with a useEffect() hook

What is a commonly used prop that's built into the Provider component?

value

Does .json() also return a promise?

yes

Is a function an object? Why does this matter in relation to useEffect?

yes It matter because if you point at a function and thus add it as a dependency it will create an infinite loop because every time an object is re-rendered it is technically a different object (just with the same appearance), and the purpose of useEffect is to re-render when one of it's dependencies change.

Is the component function re-executed when the state is updated?

yes.

How do you implement error handling in async functions? How when using .then?

you can just chain .catch() onto .then() With async you must use try {} catch (error) {}


संबंधित स्टडी सेट्स

MBE (Torts, Con law, Crim law/Crim Pro

View Set

Chapter 24 The origin of species

View Set

Modern World History Patterns Final

View Set

Hospitalized Adult Assessment PrepU

View Set

Need a New Drug? Exam 2 Study Guide

View Set

Chapter 3: Collecting Objective Data: The Physical Examination PrepU

View Set