React/JavaScript/TypeScript Flashcards

1
Q

Hook Rule: Only Call Hooks at the Top Level. | Hooks cannot be conditional
Why?

A

Do not call Hooks inside loops, conditions, or nested functions
React relies on the ORDER in which Hooks are called to associate Hook state and effects with the component rendering them. If you call Hooks conditionally or inside loops, it could break this order and lead to unexpected behaviors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Hook Rule: Only Call Hooks from React Functions. Why?

A

DO NOT call Hooks from regular JavaScript functions. Instead, call Hooks from React function components, or from custom Hooks.

The state and effects from Hooks are persisted across renders. If you were to call a Hook conditionally or from a regular JavaScript function, React wouldn’t know how to preserve this state or which state corresponds to which Hook between renders.

This will help to ensure that your hooks are used correctly and that React can properly maintain the state of your components.

This ensures that all stateful logic in a component is clearly visible from its source code.

Use custom hooks to encapsulate complex logic.
This can help to make your code more readable and maintainable.

Hooks were designed to work with React’s rendering and diffing algorithms. Calling them outside the context of a React function component would not make sense and could lead to unpredictable behaviors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Hook Rule: Keep the Body of a Hook Plain.

Why?

A

Avoid putting anything other than Hook calls and basic calculations in the body of your function component or custom Hook. Instead, use useEffect for side effects, and use functions passed to setters (like setState(prevState => newState)) for complex state logic.

Keeping the body of your Hooks and components plain helps prevent unnecessary re-renders and makes the components more predictable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Hook Rule: Use the ESLint Plugin

Why?

A

Use the eslint-plugin-react-hooks to enforce these rules.

This ESLint plugin helps catch violations of the rules, ensuring that your components adhere to best practices and that you avoid potential pitfalls.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can you put useState in an if function?

A

NO, you should not use useState (or any other Hook) inside conditions, loops, or nested functions within a React component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Explain Consistency and Predictability in Hook Execution Order

A

React relies on the order in which Hooks are called between multiple renders of a component to maintain the state and other associated values correctly.

If you put a Hook like useState inside a condition, it might not get executed in some renders, leading to inconsistencies in the order of Hook calls between renders. This can cause unexpected behaviors and bugs in your component.

Ensuring Hooks are always called in the same order makes your components more predictable and easier to understand. It ensures that stateful logic is visible and consistent every time the component renders.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Is useState async/sync and why or why not?

A

When you call the state update function returned by useState, it schedules a re-render of the component, but it doesn’t force an immediate re-render synchronously.

If you have multiple setState calls, React will group them together and re-render the component once, rather than re-rendering for every state change. This batching happens especially in event handlers and lifecycle methods in class components. This is done to optimize performance.

While useState itself isn’t asynchronous, it’s important to remember that state updates might be asynchronous in nature. Therefore, when you’re updating the state based on the previous state, you should use the functional form of setState:

setCount(prevCount => prevCount + 1);

This ensures that you’re always working with the most recent state value.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is JSX?

A

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. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance.

JSX gets compiled to REACT.CREATEELEMENT() calls which return plain JavaScript objects. It gives us expressiveness of JavaScript along with HTML like template syntax.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why is class, className in React?

A

The reason why React uses className instead of class is because class is a reserved keyword in JavaScript

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Describe data flow in React?

A

Data flow in React is unidirectional, which means that data can only flow from one component to another in a single direction. This helps to ensure that state is managed in a predictable and controlled way.

The main way data flows in React is through props. Props are passed from parent components to child components, and they can be used to pass data down the component hierarchy.

State is another way data can flow in React. State is data that is managed by a component, and it can be used to store things like the current user input or the current state of a component.

The data flow in React can be summarized as follows:
1. User interacts with UI.
2. UI component dispatches an event.
3. Event is handled by event handler.
4. Event handler updates state.
5. State is updated in component.
6. Component is re-rendered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

.

A

.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

.

A

.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How is state updated?

A

Actions are a way of updating state. Actions are functions that are called to update the state of a component. When an action is called, it will usually dispatch an event, which will then be handled by the component’s state machine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you delay an API call until a component is mounted?

A

In React, you often make API calls in the componentDidMount() lifecycle method for class components or the useEffect() hook for function components

The useEffect hook takes two arguments: a function containing the code to run and a dependency array. The empty dependency array ([]) ensures that the code inside the useEffect runs only once, similar to componentDidMount.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Explain the useEffect hook

A

The useEffect hook allows you to run code after a component has mounted or when its props or state change.

The useEffect hook takes two arguments: the first argument is a function that will be run when the component mounts or when its props or state change, and the second argument is an array of dependencies.

The array of dependencies is used to determine when the function will be run. If the array of dependencies is empty, the function will be run once when the component mounts. If the array of dependencies contains a prop or state value, the function will be run whenever that prop or state value changes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

.

A

.

17
Q

Explain the Suspense component.

A

The Suspense component is a new feature in React that allows you to wait for data to be loaded before rendering a component. To use the Suspense component to delay an API call, you can use the following code:

<Suspense fallback={<Loading />}>
             <Component />
</Suspense>

The Suspense component takes two arguments: the first argument is the component that you want to render, and the second argument is the fallback component that will be rendered while the data is loading. The Suspense component will wait for the data to be loaded before rendering the component. If the data is not loaded yet, the fallback component will be rendered.

18
Q

Should you use a ternary or && to conditionally render components?

A

The first (and the best) way is to use the ternary operator. when using the && operator with falsey values like 0 and NaN - it can accidentally cause unexpected rendering issues

19
Q

What is a closure in JavasScript?

A

A function that has access to the parent scope’s variables, even after the parent function has completed execution.

In JavaScript, functions are executed using the scope chain created when the function is defined. This means that a function defined inside another function has access to the outer function’s variables. This behavior is referred to as lexical or static scoping.

20
Q

Explain Hoisting

A

Hoisting is a behavior in JavaScript in which variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed.

This behavior allows variables and functions to be used before they’re declared in the code. However, it’s important to note that while declarations are hoisted, initializations are not.

When you declare a variable using var, the declaration (but not the initialization) is hoisted to the top of its scope. This means that the variable can be used before its declaration, but it will be undefined until the line where it is initialized.

console.log(myVar); // Outputs: undefined
   var myVar = 5;
   console.log(myVar); // Outputs: 5

Function declarations are hoisted to the top of their scope with both their name and body.
greeting(); // Outputs: "Hello!"
   function greeting() {
       console.log("Hello!");
   }

Here, the entire greeting function declaration is hoisted, allowing it to be called before its position in the code.

While variables declared with var are hoisted, variables declared with let and const in ES6 are also hoisted but they are not initialized to undefined. Accessing them before their declaration in the code results in a ReferenceError.

console.log(myLetVar); // Results in ReferenceError
   let myLetVar = 10;
21
Q

.

A

.

22
Q

.

A

.

23
Q

.

A

.

24
Q

What is an async call?

A

In JavaScript, asynchronous operations allow you to perform non-blocking tasks, meaning the execution can proceed without waiting for the async task to complete

25
Q

What are different ways to make async call?

A

Callbacks. Promises. Async/Await. Generators. Event Listeners. Web Workers. Ajax (XMLHttpRequest)

26
Q

How do you use a callback in JS to perform an async call?

A

The traditional way to handle asynchronous actions. A callback is a function passed as an argument to another function, which will be executed once the primary operation is complete.

Example using Node.js’s fs module to read a file:

const fs = require('fs');
   fs.readFile('example.txt', 'utf8', (err, data) => {
       if (err) throw err;
       console.log(data);
   });
27
Q

How do you use a Promise in JS to perform an async call?

A

A Promise represents a value that might not be available yet. It allows you to associate handlers with an asynchronous action’s eventual success or failure. Promises have three states: pending, resolved (fulfilled), or rejected. You handle the outcome of asynchronous operations using the .then() method for fulfillment, and the .catch() method for rejection.

Example:

let myPromise = new Promise((resolve, reject) => {
              setTimeout(() => {
                   resolve("Promise resolved");
              }, 1000);
});
myPromise.then(result => console.log(result))
.catch(error => console.log(error));
28
Q

How do you use a async/await in JS to perform an async call?

A

Makes it possible to write asynchronous code that looks and behaves like synchronous code. The async/await syntax is built on top of Promises, but it offers a more readable and concise way to work with asynchronous operations in a synchronous-like manner.

When you prepend a function definition with the async keyword, it ensures that the function returns a promise. Even if you return a non-promise value from the function, it’ll be wrapped in a resolved promise

Inside an async function, you can use the await keyword before any promise-based function. This will pause the async function execution until the promise is settled (either resolved or rejected), then resume the execution and return the resolved value.

With async/await, you can use traditional try/catch blocks

Example:

async function fetchData() {
       try {
           let response = await fetch('https://api.example.com/data');
           let data = await response.json();
           console.log(data);
       } catch (error) {
           console.log('Error fetching data:', error);
       }
   }
fetchData();
29
Q

How do you use generators in JS to perform an async call?

A

Functions that can be paused and resumed, allowing other code to run in the meantime. Used with the function* declaration and the yield keyword. Can be combined with Promises to handle async operations.

Example:

function* generatorFunction() {
       let data = yield fetchData(); // fetchData returns a Promise
       console.log(data);
   }
30
Q

How do you use event listeners in JS to perform an async call?

A

Can be used to handle events asynchronously. When an event occurs, the provided callback function is executed.

Example:

document.addEventListener('click', (event) => {
       console.log('Document was clicked!', event);
   });
31
Q

How do you use web workers in JS to perform an async call?

A

Allows running JavaScript code in the background, on a separate thread, without blocking the main thread. Useful for heavy computations that might block the UI.

Example:

let worker = new Worker('worker.js');
   worker.onmessage = function(event) {
       console.log('Received data from worker:', event.data);
   };
32
Q

How do you use AJAX in JS to perform an async call?

A

Ajax (XMLHttpRequest): Historically used to fetch data from servers without a full page refresh. Has been largely superseded by the fetch API but is still relevant in some contexts

Example:

let xhr = new XMLHttpRequest();
   xhr.open('GET', 'https://api.example.com/data');
   xhr.onload = function() {
       console.log(JSON.parse(xhr.response));
   };
   xhr.send();
33
Q

Explain what is a Promise

A

A Promise is a proxy for a value that might not be known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success or failure.

A Promise has three states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed).

You handle the outcome of asynchronous operations using the .then() method for fulfillment, and the .catch() method for rejection.

let myPromise = new Promise((resolve, reject) => {
       setTimeout(() => {
           resolve("Promise resolved");
       }, 1000);
   });
myPromise
       .then(result => console.log(result))
       .catch(error => console.log(error));
34
Q

Explain async/await

A

The async/await syntax is built on top of Promises, but it offers a more readable and concise way to work with asynchronous operations in a synchronous-like manner.

When you prepend a function definition with the async keyword, it ensures that the function returns a promise. Even if you return a non-promise value from the function, it’ll be wrapped in a resolved promise.

Inside an async function, you can use the await keyword before any promise-based function. This will pause the async function execution until the promise is settled (either resolved or rejected), then resume the execution and return the resolved value.

async function fetchData() {
try {
let response = await fetch(‘https://api.example.com/data’);
let data = await response.json();
console.log(data);
} catch (error) {
console.log(‘Error fetching data:’, error);
}
}

fetchData();

35
Q

List the rules using hooks in React.

A
  1. Hooks can only be called from React function components (not class components or from regular JavaScript functions).
  2. Hooks can only be called at the top level of a component (not inside loops, conditionals or nested functions)
  3. Hooks cannot be conditional.

Note: using the ESLint Plugin also helps to enforce the rules and ensure adherence to best practices.