React + Node + Next.js

¡Supera tus tareas y exámenes ahora con Quizwiz!

What are the differences between the Real DOM and the Virtual DOM?

1. The Virtual DOM updates faster than the Real DOM. 2. The Real DOM can directly update HTML whereas the Virtual DOM can't. 3. The Real DOM creates a new DOM when an element updates whereas the Virtual DOM updates the JSX. 4. DOM manipulation with the Virtual DOM is much less expensive than with the Real DOM.

What is async/await in Node.js (w/ pros and cons)?

Async/await is a syntax introduced in ECMAScript 2017 (ES8) that simplifies asynchronous code by using promises. Pros: - Improved readability and maintainability by writing asynchronous code in a synchronous style. - Reduced nesting and flatter code structure compared to callbacks and even promises. - Error handling is more straightforward and can be done using try-catch blocks. - Makes it easier to work with loops and conditionals in asynchronous code. Cons: - Requires a JavaScript environment that supports async/await (Node.js 8+ or modern browsers). - The code will need to be transpiled if targeting older JavaScript versions. - May introduce some additional overhead in terms of performance compared to promises.

Why can't browsers read JSX? What is the process that allows it to be read?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

What is the purpose of render() in React?

Each React component must have a render() method. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag. This function must be kept pure i.e., it must return the same result each time it is invoked.

What are error boundaries?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

What is Express.js?

Express.js, is a back end web application framework for Node.js, released as free and open-source software. It is designed for building web applications and APIs.

What is the difference between a controlled component and an uncontrolled component?

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself. To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax.

What is React?

React is an open source front-end JavaScript library developed by Facebook in 2011. It follows a component based approach which allows us to create reusable UI components.

What are some security considerations when developing a Node.js application?

Some security considerations when developing a Node.js application include validating input data, sanitizing user input, using secure authentication and authorization mechanisms, using SSL/TLS to encrypt communications, and keeping software and dependencies up-to-date.

What are streams in Node.js?

Streams are a built-in feature in Node.js that allow for efficient processing of large amounts of data by breaking it up into smaller chunks. There are four types of streams in Node.js: Readable, Writable, Duplex, and Transform.

What is the purpose of the "exports" object in Node.js?

The "exports" object in Node.js is used to expose a module's functionality to other parts of a Node.js application. It allows developers to create reusable code that can be easily shared.

What is the "process" object in Node.js?

The "process" object in Node.js is a global object that provides information about the current Node.js process. It allows developers to interact with the environment in which their Node.js application is running.

What is the role of the "require" function in Node.js?

The "require" function in Node.js is used to include modules in a Node.js application. It allows developers to reuse code and keep their applications modular.

What is the purpose of the Next.js Link component?

The Link component in Next.js is used for client-side navigation between pages. It prefetches the required JavaScript code and assets for the linked page, enhancing performance and user experience. It's recommended to use the Link component instead of traditional anchor tags (<a>) for internal navigation within a Next.js application.

Explain the statement "in React, everything is a component".

The building blocks of a React application's UI are called components. Any app UI created using React is divisible into a number of small independent and reusable pieces, known as components. React renders each of the components independent of each other. Hence, there is no effect of rendering a component on the rest of the app UI.

What are the phases of a React component's lifecycle?

The component lifecycle has three distinct lifecycle phases: Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods. Updating: In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods. Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.

What is the purpose of the useEffect hook in React?

The useEffect hook is used to manage side effects in functional components, such as fetching data, updating the document title, or setting up and tearing down event listeners. It allows developers to perform these side effects after rendering has occurred, and can also be used to clean up after these effects when the component unmounts.

How do you optimize the performance of a Node.js application?

To optimize the performance of a Node.js application, developers can use techniques such as caching, asynchronous I/O, clustering, and using a load balancer. It's also important to monitor the application's performance and identify and fix bottlenecks.

How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

How do you update the state of a component?

We must use this.SetState({ key: value }) to update the state since this function makes the component re-render to represent the new state. Using this.state.key = value will not re-render the component so the state change won't be reflected to the user.

What is an event loop in Node.js?

Whenever we run a Node program, a thread is automatically created. This thread is the only place where our entire codebase is going to be executed. Inside of it, something called the event loop is generated. The role of this loop is to schedule which operations our only thread should be performing at any given point in time.

How do you create a simple Express.js application?

const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })

What is the difference between useMemo and useCallback hooks in React?

useMemo is used to memoize the result of a function, so that it is only re-computed when its dependencies change. useCallback is used to memoize a function itself, so that it is only re-created when its dependencies change. useMemo is useful for expensive calculations that need to be cached, while useCallback is useful for avoiding unnecessary re-renders of components that depend on functions.

What is the difference between "let" and "var" in Node.js?

"let" and "var" are both used to declare variables in Node.js, but "let" is block-scoped while "var" is function-scoped. This means that variables declared with "let" are only accessible within the block in which they are defined, while variables declared with "var" are accessible within the entire function in which they are defined.

What is the package.json file used for?

A package.json is a JSON file that exists at the root of a Node project. It holds metadata relevant to the project and it is used for managing the project's dependencies, scripts, version, etc.

How do you handle errors in Node.js?

In Node.js, errors can be handled using try-catch blocks, callbacks, promises, or async/await. It's important to handle errors properly to prevent crashes and improve the reliability of the application.

What are the differences between functional and class components?

1. A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element. A class component requires you to extend from React. Component and create a render function which returns a React element. 2. There is no render method used in functional components. Class components must have the render() method returning JSX. 3. Functional components are known as Stateless components as they simply accept data and display them in some form, that they are mainly responsible for rendering UI. Class components are also known as Stateful components because they implement logic and state. 4. React lifecycle methods (for example, componentDidMount) cannot be used in functional components whereas they can be used in class components.

What are the features of React?

1. It uses the Virtual DOM to handle updates and changes in state. 2. It supports server-side rendering. 3. It follows unidirectional data flow. 4. Uses reusable/composable UI components.

What are the steps of loading a React application in the browser?

1. The browser sends an HTTP request to the server to retrieve the HTML file that contains the React application. The server sends back the HTML file, which includes a reference to the JavaScript file that contains the React application code. 2. The browser parses the HTML file and detects the reference to the JavaScript file. 3. The browser sends additional HTTP requests to download the referenced JavaScript files. 4. The JavaScript files are downloaded and parsed by the browser. 5. React uses the virtual DOM to render the initial view of the application. 6. The browser displays the initial view of the application. 7. As the user interacts with the application, React updates the virtual DOM and compares it with the previous version to determine what changes need to be made to the actual DOM. 8. The browser updates the DOM to reflect the changes made by React. 9. The user continues to interact with the application, and the process repeats. It's worth noting that if the React application uses server-side rendering (SSR), some of these steps may occur on the server rather than in the browser. For example, the server may generate the initial HTML file that includes the React application code, and then send it to the browser to be rendered.

List some of the major advantages of React.

1. The use of the Virtual DOM improves efficiency. 2. Server-side rendering can boost the SEO of an app. 3. Reusable components increase the pace of development since they can be composed and even shared across different apps. 4. There is a huge ecosystem of libraries and tools to choose from that can be integrated into React apps.

What are higher order components? When are they used?

A Higher Order Component (HOC) is a function that takes in a component and returns a new component. This can be useful if we want to create two components that are similar in their functionality but display different types of data or have slight differences. In order to render similar components that display users and articles, we can create a function HOC that takes in the component name and API call for each and returns a similar component for each with the respective data from the API call. const UsersListWithHOC = HOC(UsersList, (API) => API.getUsers()); const ArticlesListWithHOC = HOC(ArticlesList, (API)=> API.getArticles());

What are callbacks in Node.js (w/ pros and cons)?

Callbacks are the traditional approach to handle asynchronous operations in JavaScript. Pros: - Simple and widely supported across JavaScript environments. - Can be used with any JavaScript version, including older ones. Cons: - Can lead to callback hell or pyramid of doom, where nested callbacks make the code hard to read and maintain. - Error handling can become cumbersome. - Lack of built-in control flow constructs like loops and conditionals.

What are the benefits of using Next.js over a traditional React application?

Improved performance: Next.js provides server-side rendering and automatic code splitting, resulting in faster initial page loads and optimized performance. SEO-friendly: Server-side rendering in Next.js enables search engine crawlers to easily index your content, improving search engine visibility. Simplified routing: Next.js uses file-based routing, where each file in the pages directory corresponds to a specific route, eliminating the need for manual route configuration. Built-in optimizations: Next.js automatically optimizes the production build with features like code splitting, prefetching, and lazy loading, enhancing performance and user experience.

Explain context.

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree. In order to use the Context API, you have to create a context using the React.createContext() function and then set the context values in a Context.Provider element. You can then access the context values from components that are nested within the provider by either using static contextType = MyContext or creating a MyContext.Consumer element with which to wrap the consumer component.

What are pure components?

In pure components, if the previous value of state or props and the new value of state or props is the same, the component will not re-render itself, since Pure Components restrict the re-rendering when there is no use of re-rendering of the component. Pure Components are Class Components which extends React.PureComponent.

What are modules in Node.js?

Modules in Node.js can be used to organize functionality into single or multiple JavaScript files which can be reused throughout the application. Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope. Node uses CommonJS behind the scenes which provides the "require" and "exports" syntax in order to import and export data and functions between files.

What is NPM?

NPM is two things: first and foremost, it is an online repository for the publishing of open-source Node. js projects; second, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management.

How can you handle API requests in Next.js?

Next.js provides an easy way to handle API requests using the api directory. Any file inside the pages/api directory is treated as an API endpoint. You can define serverless API routes to handle different types of requests, such as GET, POST, or PUT.

How do threads work in Node.js?

Node.js is a single threaded runtime meaning that there is only one call stack and only one set of instructions is executed at a time. In the background, Node.js can actually use multiple threads to execute asynchronous code with the help of the libuv library. Libuv sets up a thread pool of four threads to perform OS-related operations by utilizing the power of all the CPU cores. Given our machine has four cores, each thread from the pool is assigned to every core. This is generally used for operations that are too heavy for the event loop to handle. If the same function is run four times, all four functions can execute at the same time since each is given to a separate thread. Within this four core machine, if we run the same function five times, the fifth call would take longer to run because it would have to wait for one of the four threads to complete their tasks before taking on the fifth call.

What is Node.js?

Node.js is an open-source, Javascript runtime environment on Chrome's V8 that lets you develop fast and scalable web applications. It utilizes an event-driven, non-blocking I/O model that makes it lightweight, efficient and excellent for data-intensive real-time applications.

What is the event-driven architecture in Node.js?

Node.js uses an event-driven architecture where functions are executed in response to certain events or actions. This allows Node.js to handle multiple concurrent requests efficiently.

What are promises in Node.js (w/ pros and cons)?

Promises provide a structured way to handle asynchronous operations and are built upon the concept of callbacks. Pros: - Improved readability and code organization compared to callbacks. - Allows chaining of multiple asynchronous operations using methods like .then() and .catch(). - Provides better error handling and separation of success and error paths. - Support for parallel or sequential execution of multiple promises using methods like Promise.all() or Promise.race(). Cons: - Requires support for Promises, which means older JavaScript environments may require a polyfill. - Can still lead to some level of nesting if complex control flow is involved. - Handling synchronous errors within a promise requires additional error handling.

What is prop drilling in React? How can it be avoided?

Prop drilling is the process by which you pass data from one part of the React Component tree to another by going through other parts that do not need the data but only help in passing it around. Prop drilling can be avoided by using the Context API which allows you to set a "global" context of key value pairs in the context provider that you can then use in its child components.

What are props?

Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.

What are some pros and cons of Node.js?

Pros: 1. Robust technology stack 2. Fast processing due to use of V8 engine 3. Efficient asynchronous request handling due to non-blocking nature 4. Scalable and a good choice for microservice architecture due to it being lightweight and fast 5. Rich ecosystem (NPM) Cons: 1. Not great for heavy computation or CPU bound tasks 2. Callback hell issue since Node relies on callback functions a lot 3. Some NPM modules may be poorly documented or poorly tested and there isn't much regulation on what's out there so you could end up with poorly made dependencies

What is React Router?

React Router, and dynamic, client-side routing, allows us to build a single-page web application with navigation without the page refreshing as the user navigates. React Router uses component structure to call components, which display the appropriate information. By preventing a page refresh, and using Router or Link, the flash of a white screen or blank page is prevented. This is one increasingly common way of having a more seamless user experience. React router also allows the user to utilize browser functionality like the back button and the refresh page while maintaining the correct view of the application.

What is the difference between React and Next.js?

React is a JavaScript library for building user interfaces, while Next.js is a framework that extends React with server-side rendering, routing, and other features required for building complete web applications. Next.js simplifies the development process by providing an opinionated structure and built-in solutions for common web development challenges.

How does SSR work in Next.js?

Server-side rendering (SSR) is a technique for generating HTML content on the server and sending it to the client. Here are the steps involved in server-side rendering: 1. Client requests a page: When a client requests a page from a server, the server receives the request and initiates the server-side rendering process. 2. Server generates HTML: The server-side rendering process involves running the application code on the server, which generates HTML markup based on the requested page and its data. 3. Server sends HTML to the client: Once the HTML markup is generated, the server sends it to the client as the initial response. This allows the client to display the content of the page immediately, without waiting for JavaScript to load and render the content. 4. Client loads JavaScript: Once the HTML is received, the client loads the JavaScript code that is required for interactivity, event handling, and other dynamic behaviors of the page. 5. Client hydrates the page: The client-side JavaScript code takes over and "hydrates" the page, which means it adds interactivity and behavior to the HTML markup that was generated on the server. The client-side code re-renders the page with additional data, if required, and makes it fully interactive. Server-side rendering can improve the initial page load time by reducing the amount of JavaScript that needs to be downloaded and parsed by the browser. It can also improve the search engine optimization (SEO) of web applications by providing crawlers with fully-rendered HTML pages. Server-side rendering can be implemented using various technologies, such as Node.js, PHP, Java, Ruby, and others. Different frameworks, such as Next.js, Nuxt.js, and React Server Components, provide built-in support for server-side rendering.

What are the different rendering modes in Next.js?

Server-side rendering (SSR): Each page is rendered on the server and sent as HTML to the client, providing faster initial load times and search engine optimization. Static site generation (SSG): Pages are generated at build time and served as static HTML files, allowing for highly performant and scalable websites. Client-side rendering (CSR): Pages are rendered on the client-side using JavaScript after the initial HTML load. This mode is useful for dynamic content or interactive elements.

What is server-side rendering in React and why would you use it?

Server-side rendering is the process of rendering a React application on the server and sending the resulting HTML to the client instead of sending just the JavaScript bundle. This can improve performance and SEO, as the user can see content faster and search engines can index the page more easily. To implement server-side rendering in React, you can use libraries like Next.js or Gatsby.

What is server-side rendering?

Server-side rendering is the process of taking a client-side JavaScript framework website and rendering it to static HTML and CSS on the server. This is a tool to get the website to render faster. With server-side rendering, you can generate the HTML on the server and send that to the browser so that the user can see the HTML version of the app almost immediately as the JS app boots up in the background. At this point, the app will be visible to the user but not interactive until the JS is parsed and executed. There are ways in which this can be set up (e.g. using a cache) in order to make the TTI (time to interactive) quicker.

What is the difference between shallow rendering and full rendering in React testing?

Shallow rendering in React testing involves rendering only the top-level component without rendering its children, while full rendering involves rendering the entire component tree. Shallow rendering can be faster and more efficient, but may not catch all possible bugs or issues. Full rendering provides a more comprehensive test, but can be slower and more resource-intensive.

What is state in React and how is it used?

State of a component is an object that holds some information that may change over the lifetime of the component. State is similar to props, but it is private and fully controlled by the component. i.e, It is not accessible to any component other than the one that owns and sets it.

How does Node.js work?

The Node.js runtime works pretty similarly to the browser JS runtime. It also uses the V8 engine, an event loop, and a callback queue. It uses something called the LIBUV written in C++ that allows us to do asynchronous operations. Node can do more than the browser when it comes to what we can do in the background since it isn't running in a sandboxed environment (e.g. access file systems). Instead of the window object, Node.js has a global object that contains its API, similar to the web API but with some extended functionality.

What is the difference between server-side rendering and static site generation?

The main difference between SSR and SSG lies in when the rendering occurs. SSR renders pages dynamically on each request, while SSG generates static HTML files during the build process, which are served to the client without the need for server-side rendering. SSG is better for blogs or documentation sites where the content doesn't change often. SSR is better for dynamic websites, since it renders pages based on requests.

Explain refs in React. When are they used and how do you create a ref?

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component. Example of use: in D3.js it is preferable to attach a graph to a div using a ref of that div for it to always render correctly. How to create a ref: add this.myRef = React.createRef() to the constructor and then attach it to the div using ref ={this.myRef} as a property.

What is the purpose of the useReducer hook in React and how would you use it?

The useReducer hook in React is used to manage state in a more complex or structured way than useState. It takes a reducer function that updates state based on a dispatched action object, similar to how reducers work in Redux. To use the useReducer hook, you would define a reducer function that takes a current state and an action object and returns a new state, and use it with the useReducer hook to manage state in a component.

How does the Virtual DOM work?

When there is a change in state that affects the DOM, React first updates the Virtual DOM to reflect this change. Two Virtual DOMs exist for each React app, one of which stores a representation of the DOM after these updates while the other one stores a representation of the DOM before the updates. React then uses a process called reconciliation to create a diff of the two Virtual DOMs by comparing them. Every difference between the two is then rendered in the Real DOM which allows us to update only the elements that have changed instead of re-rendering the entire Real DOM which can be pretty expensive and inefficient.

What are synthetic events in React?

Whenever you call an event handler within ReactJS, they are passed an instance of SyntheticEvent instead of the native event handler. This has the same interface as the native event handler's, except it's cross-browser compatible so you can use it without worrying whether you need to make exceptions in your code for different browser implementations.

What is the syntax to use a ref inside a functional component?

const myRef = useRef() <div ref={myRef}>Hi</div> To access ref value: myRef.current

What is the purpose of getStaticPaths in Next.js?

getStaticPaths is a function used in Next.js for dynamic routes when using static site generation (SSG). It allows you to specify dynamic parameters in the URL and define which paths to pre-render at build time. This is useful when you have pages that depend on data that isn't available until runtime.

How can you fetch data in Next.js?

getStaticProps: This function is used for static site generation (SSG) and fetches data at build time. getServerSideProps: This function is used for server-side rendering (SSR) and fetches data on every request. useEffect: For client-side rendering (CSR), you can use the useEffect hook to fetch data after the component mounts.

What is the difference between useState and useRef in React?

useState is used to create state variables in a functional component. It returns an array with two elements: the current state value and a function to update the state value. When the state value is updated, React will re-render the component and display the updated value. On the other hand, useRef is used to create a mutable reference that persists between component renders. It returns a single object with a current property that can be used to store and access a value that persists between component renders. Unlike useState, updating the current property of a useRef object will not trigger a re-render of the component.


Conjuntos de estudio relacionados

Conceptual Physics study guide modules 5,6,7,1

View Set

Lektion 13 - wann, wenn oder als? (Grammatik)

View Set

Conceptual Physical Science Final Exam: Chapter 28: The Structure of Space and Time

View Set

GENERAL MATHEMATICS LESSON, SS1 ,WEEK ONE:ALGEBRAIC PROCESSES AND EXPRESSIONS.

View Set