General Concepts Flashcards
Synchronous operations
are executed one at a time, and each operation must complete before the next one can start. In other words, synchronous operations block the execution of the program until they are finished.
asynchronous operations
do not block the execution of the program. Instead, they are designed to allow the program to continue executing other tasks while waiting for the asynchronous operation to complete.
purpose of a callback
to specify a function that will be executed or called at a later point in the program, often as a response to an event or the completion of an asynchronous operation.
setState what is does? is syncronic?
When you call setState, React will update the state object and trigger a re-rendering of the component, which means the component will update and reflect the new state.
The setState method in React is typically asynchronous. This means that calling setState doesn’t immediately update the state and re-render
this.state = {
counter: 0,
name: ‘John’
}; how to access to counter state?
this.state.counter holds the value of the counter, and this.state.name holds the value of the name.
when getDerivedStateFromProps is called?
getDerivedStateFromProps is a static method that is called before rendering and is invoked whenever the component is receiving new props or state updates.
getDerivedStateFromProps method for funtions?
It should be used for pure calculations based on props and state, without relying on any component-specific instance variables or methods.
can I use this in getDerivedStateFromProps?
is a static method, so you cannot access the this keyword or the component instance within this method
why getDerivedStateFromProps is static?
By making it static, it is enforced that the method does not have access to the component instance (this) and cannot modify any instance-specific data or invoke instance methods. meaning its output solely depends on the inputs and does not have any side effects.
what is a static method?
A static method in JavaScript is a method that belongs to a class itself rather than to an instance of the class.
what is a class?
a class is a template for creating objects of a particular type. It defines the properties (attributes) and behaviors (methods) that the objects instantiated from the
How to cretae an instance of this class?
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(Hello, my name is ${this.name} and I am ${this.age} years old.
);
}
}
const person1 = new Person(‘John Doe’, 25);
person1.sayHello();
Which are the propertes and methos od this object?
const person = {
name: ‘John Doe’,
age: 25,
sayHello: function() {
console.log(Hello, my name is ${this.name} and I am ${this.age} years old.
);
}
};
In this example, the person object has two properties (name and age) and a method (sayHello).
is a class intance same as an object?
Yes, in the context of object-oriented programming, a class instance and an object are essentially the same thing.
what is object-oriented programming?
Object-oriented programming (OOP) is a programming paradigm that organizes code based on the concept of objects, which are instances of classes.
what is a stack
/pila?
a stack is an abstract data type that represents a collection of elements with a particular behavior known as last-in, first-out (LIFO). It is named “stack” because it resembles a stack of objects where new items are added to the top and removed from the top.
three main phases of react lifycle
mounting, updating, and unmounting.
4 methods of mounting phase
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
5 methods of Updating phase
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
1 method of Unmounting phase
componentWillUnmount()
what are the purpose of hooks?
Hooks are a feature that allows developers to use state and other React features in functional components without the need for class components.
what is jest?
Jest is a popular JavaScript testing framework developed by Facebook.
Jest is a testing framework that provides the overall test running infrastructure. It provides functionalities such as organizing your tests into suites and test cases, providing test doubles (mocks, spies, etc.), measuring code coverage, and offering utilities for assertions. Jest does not tie you to a specific way of testing and can be used with various testing approaches and libraries.
what is enzyme?
Enzyme is a JavaScript testing utility developed by Airbnb that provides additional testing capabilities for React components. It is often used in conjunction with Jest or other testing frameworks to facilitate the testing of React components in isolation. As of September 2020, Airbnb has officially announced that Enzyme development and maintenance have been discontinued.
what is react testing library?
React Testing Library is a popular testing utility for React applications that promotes testing React components in a way that resembles how users interact with the application. It emphasizes testing components based on their rendered output and behavior rather than focusing on implementation details.
prevState vs prevProps
prevState represents the previous state of a component, while prevProps represents the previous props of a component.
what is is truthy? 6
true: The boolean value true is obviously truthy.
Non-empty strings: Any string that contains at least one character is considered truthy.
Non-zero numbers: Any number that is not zero (positive or negative) is considered truthy.
Objects: Any object, including arrays and functions, is considered truthy.
Arrays: Arrays are objects in JavaScript, so they are also considered truthy.
Functions: Functions are objects as well and are considered truthy.
you can use square brackets [] to enclose the elements of …..
an array
you can use curly braces {} to enclose ….
an object.
const myObject = {
name: ‘John’,
age: 25,
city: ‘New York’,
isStudent: true,
};
what is a fetch?
fetch is a built-in function used to make asynchronous network requests and retrieve resources from a specified URL. The fetch function takes a URL as its first argument and returns a Promise that resolves to the response of the request.
how is a fetch structure? 3 parts
fetch(url)
.then(response => {
// Handle the response
})
.catch(error => {
// Handle any errors
});
what is response.json in a fetch?
In the fetch function, the response.json() method is used to extract the response data as JSON. It returns a Promise that resolves to the parsed JSON data from the response body.
fetch(‘https://api.example.com/data’)
.then(response => response.json())
.then(data => {
// Handle the parsed JSON data
console.log(data);
})
.catch(error => {
// Handle any errors
console.error(‘Error:’, error);
});
how is the json format?
it variaety that is why we have JSON.stringify() function is used to convert JavaScript objects into JSON strings, while JSON.parse() is used to parse a JSON string and convert it into a JavaScript object.
what is a script?
A script is typically used to automate tasks or perform specific operations. It can be written to interact with a system, manipulate data, control the behavior of a program, or perform various other functions.
Popular scripting languages include JavaScript, Python, Ruby, Perl, Bash, PowerShell, and many others.
give an example of a class and class intances with a car
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self): print(f"Make: {self.make}, Model: {self.model}, Year: {self.year}")
Creating car instances
car1 = Car(“Toyota”, “Camry”, 2020)
car2 = Car(“Honda”, “Civic”, 2018)
car3 = Car(“Ford”, “Mustang”, 2022)
Are objects same as class?
Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity.
How does fetch works with a promise?
To get data using promises in JavaScript, you typically use the fetch() function, which returns a promise that resolves to the response of the HTTP request.
fetch(‘https://api.example.com/data’)
.then(response => response.json()) // Parse the response as JSON
.then(data => {
// Work with the data
console.log(data);
})
.catch(error => {
// Handle any errors that occurred during the request
console.error(‘Error:’, error);
});
¿Qué es ESLint?
ESLint es una herramienta de código abierto enfocada en el proceso de “lintig” para javascript (o más correctamente para ECMAScript). ESLint es la herramienta predominante para la tarea de “limpiar” código javascript tanto en el servidor (node. js) como en el navegador.
“Linting” es un proceso que se realiza en la etapa de desarrollo para verificar el código y encontrar cualquier problema potencial. Un “linter” es una herramienta que se usa en este proceso.
El linter realiza varias comprobaciones en el código, como la detección de errores de sintaxis, errores de formato, errores de estilos de codificación y otros problemas posibles.
Un linter muy popular para JavaScript es ESLint. Puedes personalizar las reglas de ESLint según tus necesidades, lo que significa que puedes definir tus propios estándares de estilo de código y hacer que ESLint verifique el código en consecuencia.
What is npm?
npm comes bundled with it.
With npm, you can:
Author your own Node.js modules (“packages”), and publish them on the npm website so that other people can download and use them
Use other people’s authored modules (“packages”)
So, ultimately, npm is all about code sharing and reuse. You can use other people’s code in your own projects, and you can also publish your own Node.js modules so that other people can use them.
Que es deploy?
Deployment is the mechanism through which applications, modules, updates, and patches are delivered from developers to users.
What package.json is?
The package. json file is the heart of any Node project. It records important metadata about a project which is required before publishing to NPM, and also defines functional attributes of a project that npm uses to install dependencies, run scripts, and identify the entry point to our package.
3 things to do with new code in j***s
The methods used by developers to build, test and deploy new code.
Code in dev
-You can check which git commit the code has been put in dev from.
Dev enviroment
A development environment in software and web development is a workspace for developers to make changes without breaking anything in a live environment.
Production enviroment
A production environment is a real-time setting where the latest versions of software, products, or updates are pushed into live, usable operation for the intended end users.
You deploy to…
enviroments….
could be dev, uat, uat2…
What does j***s does?
you can deploy, is a pipeline that has a code commit source, then a build, a test and a deply to the desire enviroment.
What are props? aka properties
which stands for properties and is being used for passing data from one component to another. But the important part here is that data with props are being passed in a uni-directional flow. IMMUTABLE BY CHILDS
What is a state?
The state is a built-in React object that is used to contain data or information about the component. A component’s state can change over time; whenever it changes, the component re-renders.
When a components re-renders?
React components automatically re-render whenever there is a change in their state or props.
CONTEXT API- useContext
to avoid props drilling porblems to super grand childrends :(, like red hairs!
for global states
Example of useContext dark/light theme in an website
affect all the components and all components should known the state. Is a GLOBAL STATE.
SHARE Global data :)
Tipical, userPermission according to id
GLOBAL STATES: You need (3)
-create a context
-useContext
-provider for the context
-then you can access from x component to that needed state of the context.
-you create a global state
theme.provider or x.provider. What it does?
The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider.
memoization, const value = useMemo(() => ({a, b}), [a, b]);
what is for?
avoiding unnecessary rendering when two props are the same but different objects
Statefull component
Needs states, just like input of my fav coutries to live in!
Stateless component
dosent have states, it could use props!
props drilling! We hate… we fix with…
useContext :)
uncontrolled component
is a component that maintains its own internal state. No component re-renders.
Browser DOM handles the changes to the element.
If you are using a form, you are NOT using setState to capture input. Instead you could be using useRef hook to capture node value, current.value. Is an state matain by the DOM
controlled component
a controlled component is a component that is controlled by React state. Ex. form input use UseState to update input values and save it as internal state of the component
array destructuring Example :)
Destructuring the array in JavaScript simply means extracting multiple values from data stored in objects and arrays
object destructuring
Destructuring the array in JavaScript simply means extracting multiple values from data stored in objects and arrays
object destructuring
array of objects, how to write it?
const array = [
{id:1, name: “Peter”},
{id:2, name: “John”}
]
how to map over an array of objects and show the name?
{asianCountries.map(( x, y )=>
<ul>{xxx}</ul>)}
{asianCountries.map((country, id )=>
<ul>{country.name}</ul>)}
order of country and id,
country.name
4 basic html things for a form:
- form
- label
- input
- button
useState hook from React, what is and what returns?
is a function that returns an array with two elements: the current state value (in this case, an object representing a car) and a function to update that state (in this case, setCar).
what is APi?
es una interfaz que te permite “comunicar” cosas que hablan diferentes. Ej celular tipeo.
Las APIs comunican programas/sistemas entre si. Ejemplo integraciones, fb con ig, misma publicación.
Un API es un programa para ser usado por otro programa. Asi como en cualquier programa al tu interactuar con el , ingresando datos el programa te responde. Tu puedes hacer un programa que interactue con otro programa (API) y de esta manera tu programa disfrutara de los beneficios que le pueda ofrecer la AP
pure vs impure functions
Pure Functions:
A pure function is a function that always returns the same output given the same inputs. It has no side effects, meaning it does not modify external state or variables, nor does it interact with the outside world (e.g., API calls, DOM manipulation).
Pure functions are predictable and easier to reason about since they only rely on their input arguments and have no hidden dependencies.
In React, pure functions are commonly used for components that are based solely on their props. Given the same props, they always render the same output.
useEffect when it renders?
By default, if no second argument is provided to the useEffect function, the effect will run after every render.
what is a const with an arrow function in react?
a const with an arrow function refers to creating a constant variable that holds an arrow function. Arrow functions are a concise way to define functions in JavaScript, and they have a more compact syntax compared to traditional function expressions.
const sayHello = (name) => {
return ‘Hello ‘ + name;
}
what is a function?
A function is a fundamental concept in programming and refers to a reusable block of code that performs a specific task or set of tasks. Functions help in organizing code into logical and manageable pieces, making it easier to read, write, and maintain.
inputs in fucntions are called…
arguments or parameters
JS is syncronims or asyncronic?
Although it’s synchronous by nature, JavaScript benefits from asynchronous code.
Object.keys(user)
Object.keys(user) is a JavaScript method that is used to extract an array of keys from an object. In this context, it seems like user is an object, and Object.keys(user) is being used to check if the object has any properties (keys) or not.
single thread JS
Node.js runs JavaScript code in a single thread, which means that your code can only do one task at a time.
is fetching data a side effect?
fetching data from a third-party API is considered a side-effect.
what is AJAX? not football :)
AJAX = Asynchronous JavaScript
what is a reducer?
Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a reducer.
when to use useReducer and useState
useState, it’s better to use it with primitive data types, such as strings, numbers, or booleans.
The useReducer hook is best used on more complex data, specifically, arrays or objects.
what is a custum hook?
A custom hook is simply a way to extract a piece of functionality that you can use again and again.
A custom hook is essentially a JavaScript function that starts with the word use and can call other hooks. By convention, hooks always start with the word use.
when to use useReducer hook
alternative to useState, but updates different the state
manage its state with a reducer.
inspire in redux!
where the state logic is more complex and involves multiple sub-states or actions that affect each other. It can help to avoid prop drilling (passing state down through multiple layers of components) and can lead to more maintainable and predictable code.
Base on an action the state will increment or decrement.
const [state, dispatch], what is this called?
const [state, dispatch] = useReducer(reducer, initialState)
This is array destructuring in JavaScript. We are using it here to extract two values from the return value of the useReducer hook.
Extraes el stata y el dispatch del hook useReducer que devuelve un array.
where I can find JSX?
JSX allows developers to write HTML-like code within JavaScript, making it easier to create and manipulate the UI components in React applications.
JSX is used in the return statement of a React component.
what is used above the return in react?
JavaScript is commonly used above the return statement in a React component. The code above the return statement typically includes various JavaScript constructs,
what react does with components?
combines components to create a view/screen
what is a state?
values of variables you have on yoour components.
aim of npm
npm is all about code sharing and reuse. You can use other people’s code in your own projects, and you can also publish your own Node.js modules so that other people can use them.
node.js why is needed?
React itself can be used without Node.js in the client-side browser environment, having Node.js installed can greatly facilitate the development, deployment, and overall build process when working with React projects.
-js is a language that can be run in the browser, but for that needs interpretation, js enginee or babel.
-you can use node js as a server side component and enables you to use javascript as a fullstack (front and back end)
-a javascript runtime enviroment
what is react (2)?
React is just a front-end library. You’re going to need to interact with other third-party libraries.
client-side library. You do need to figure out how you’re going to do routing and server client communication.
which is react design philosphy?
component based arquitecture, for reusable component code
-colecction of components
-example: header, payment, sidebar
advantages of components? (3)
reusable
independent
stand alone parts
what is the DOM and how to edit it?
It represents a web page as a tree-like structure of objects. Each object corresponds to an HTML element or content on the page. Developers can use the DOM to interact with and modify the page’s content, structure, and style using JavaScript.
react virtual dom
tbd..
functional components acts like…
js function
index.js what is load?
the app component. Aka main component
index.html to be done
tbd
All component names must be…
capitalized, bc lowecase is seen as html elements
In return, variables, constants or states must be…
wrap around brackets {}
JSX con be defined as a combination of…
css, html and js
what is transpiling and what is babel?
-Babel: The React code, including JSX, is passed through Babel, a popular JavaScript transpiler.
-A browser cannot understand JSX syntax.
-A transpiler takes a piece of code and transforms it into some other code.
what is ES6?
JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer version of JavaScript that was introduced in 2015.
what is a website navegation?
refers to the process of navigating or moving through a website to find and access its various pages, content, and features. From component to component