React Crash Course Flashcards

1
Q

How can you use an object to hold HTML attributes and spread them into an element in React?

A

In React, you can create an object that holds various attributes for an HTML element and then use the spread operator to apply those attributes to the element.

// Create an object to hold attributes
const props = { id: 'input', type: 'text', placeholder: 'Enter text here', };

// Use the spread operator to apply attributes to the input element
return (
<input {...props} />
);

By using {…props}, all the key-value pairs in the props object will be spread as attributes into the <input></input> element. This is a convenient way to dynamically set multiple attributes on an element.

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

How can you destructure props directly in the function parameters in a React functional component?

A

In a React functional component, you can destructure props directly in the function parameters for cleaner and more readable code.

// Without destructuring
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};

// With destructuring
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};

By destructuring the props object in the function parameters, you can directly use the name variable instead of props.name. This makes the code more concise and easier to understand.

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

How can you spread props into custom components in React, such as a wrapper Button component that needs to accept attributes like type or onClick?

A

In React, you can create custom components that act as wrappers for native HTML elements. To make these custom components flexible and reusable, you can spread props into them. This allows you to pass any number of attributes to the custom component, which will then be applied to the native HTML element it wraps.

Here’s an example using a custom Button component:

// Custom Button component
const Button = ({ label, ...otherProps }) => {
return <button {...otherProps}>{label}</button>;
};

// Usage
<Button label=”Click Me” type=”submit” onClick={() => console.log(“Clicked!”)} />

In this example, the Button component accepts a label prop to display the button text. All other props (…otherProps) are spread into the native button element. This allows you to pass attributes like type, onClick, className, etc., making the custom Button component highly reusable and flexible.

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

How can you save the previous value of a state variable when calling its setter function in React?

A

Answer:
You can access the previous state value within the setter function by passing a function instead of a direct value. The function will receive the previous state as its argument.

const [count, setCount] = useState(0);

// To increment count based on its previous value
setCount(prevCount => prevCount + 1);

// To toggle a boolean value based on its previous value
const [isToggled, setIsToggled] = useState(false);
setIsToggled(prevIsToggled => !prevIsToggled);

This is particularly useful when the new state depends on the previous state. Using this approach ensures that you’re working with the most recent state.

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

What are the three main phases of a React component's life cycle?

A

Mounting: The phase when the component is being created and inserted into the DOM.

Updating: The phase when the component is re-rendered as a result of changes to either its props or state.

Unmounting: The phase when the component is being removed from the DOM.

Common life cycle methods include componentDidMount, componentDidUpdate, and componentWillUnmount.

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

What is the useEffect hook in React and how is it used?

A

The useEffect hook is used for performing side effects in functional components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount combined in class components.

useEffect(() => { // Code to run on mount or update return () => { // Cleanup code, runs on unmount }; }, [dependencies]);

The dependencies array specifies which variables the effect depends on. If they don’t change between renders, the effect won’t run.

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

What is the useLayoutEffect hook in React and how is it different from useEffect?

A

The useLayoutEffect hook is almost identical to useEffect, but it fires synchronously after all DOM mutations. This makes it suitable for reading layout from the DOM and synchronously re-rendering, avoiding flickers.

useLayoutEffect(() => { // Code to run on mount or update return () => { // Cleanup code, runs on unmount }; }, [dependencies]);

Use useLayoutEffect sparingly, as running code synchronously could be performance-intensive and cause delays in rendering.

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

What is the useRef hook in React and how is it used?

A

The useRef hook is used to access and interact with DOM elements or to keep a mutable reference to a value that doesn’t trigger a re-render when it changes. It is commonly used for focusing input fields, reading values, or integrating with third-party libraries.

const myRef = useRef(initialValue);

// Accessing DOM element
useEffect(() => {
myRef.current.focus();
}, []);

// JSX
<input ref={myRef} />

The .current property of the ref object will hold the DOM element the ref is attached to, or the value it is initialized with.

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

What is the useImperativeHandle hook in React and how is it used?

A

The useImperativeHandle hook is used to customize the instance value that is exposed to parent components when using ref. This allows you to expose only specific properties and methods to parent components, making it easier to control component behavior through refs.

import React, { useRef, useImperativeHandle, forwardRef } from ‘react’;

const MyComponent = forwardRef((props, ref) => {
const inputRef = useRef();

useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } }));

return <input ref={inputRef} />;
});

// Parent component
const ParentComponent = () => {
const myRef = useRef();

const handleFocus = () => {
myRef.current.focus();
};

return (
<>
<MyComponent ref={myRef} />
<button onClick={handleFocus}>Focus Input</button>
</>
);
};

In this example, the MyComponent exposes only the focus method to the parent component, hiding its internal implementation details.

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

What is Context in React and how is it used?

A

Context in React provides a way to pass data through the component tree without having to pass props down manually at every level. It is particularly useful for sharing state that is considered “global” for a tree of React components.

Creating Context:
const MyContext = React.createContext(defaultValue);

Providing Context:
<MyContext.Provider value={someValue}> {/* children components */} </MyContext.Provider>

Consuming Context:
1. Class Components:

class MyClass extends React.Component {
static contextType = MyContext;
render() {
const value = this.context;
/* … */
}
}

  1. Functional Components:
    import React, { useContext } from ‘react’;

const MyComponent = () => {
const value = useContext(MyContext);
return /* … */;
};

In this way, you can avoid “prop drilling” and make the state management more efficient and organized.

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

What is the key prop in React and why is it important when rendering lists of components?

A

The key prop in React is a special attribute you should provide when creating lists of elements. React uses the key to identify which items have changed, are added, or are removed, optimizing the rendering process and improving performance.

Example without key:

javascript
Copy code
const numbers = [1, 2, 3];
const listItems = numbers.map((number) => <li>{number}</li>);
Example with key:

javascript
Copy code
const numbers = [1, 2, 3];
const listItems = numbers.map((number) => <li key={number}>{number}</li>);
Usage in JSX:

javascript
Copy code

<ul>
{listItems}
</ul>

Note:

Keys should be unique among siblings.
Do not use array indices as keys if the list can change over time, as it may negatively impact performance and may cause issues with the component state.
By using the key prop correctly, you help React optimize the rendering of lists, making your application more efficient

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

What is useMemo in React and how do you use it?

A

useMemo is a React hook that memoizes the result of a function. It’s used to optimize performance by avoiding expensive calculations on every render. It takes two arguments: a function and a dependency array. The function will only be re-computed when one of the dependencies has changed.

Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Example:
import React, { useMemo } from ‘react’;

function MyComponent({ a, b }) {
const result = useMemo(() => { // Expensive computation here return a * b; }, [a, b]);

return <div>{result}</div>;
}

Note:

useMemo is useful for CPU-intensive tasks but should not be overused, as it can lead to increased memory usage.

It’s not a guarantee; React may choose to “forget” the memoized value and recalculate it in future renders for performance reasons.

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

What is useCallback in React and how do you use it?

A

useCallback is a React hook that returns a memoized version of a callback function. It’s useful for optimizing performance by preventing unnecessary renders. It takes two arguments: a function and a dependency array.

Syntax:
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);

Example:
import React, { useCallback } from ‘react’;

const MyComponent = ({ onClick }) => {
const handleClick = useCallback(() => { onClick('some data');
}, [onClick]);

return <button onClick={handleClick}>Click Me</button>;
};

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

What is React.memo and how do you use it?

A

React.memo is a higher-order component that memoizes the rendered output of a functional component, preventing unnecessary renders when the props are unchanged.

Syntax:
const MemoizedComponent = React.memo(MyComponent);

Example:
const MyComponent = React.memo(function MyComponent(props) {
// Render logic here
});

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

What is React.lazy and how do you use it?

A

React.lazy is a function that allows you to load React components lazily, as separate chunks, improving performance.

Syntax:
const LazyComponent = React.lazy(() => import('./LazyComponent'));

Example:
const LazyLoadedComponent = React.lazy(() => import('./MyComponent'));

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

What is React.Suspense and how do you use it?

A

React.Suspense is a component that lets you specify fallback content while waiting for some code to load, often used with React.lazy.

Syntax:
`<Suspense fallback={<div>Loading…</div>}>

<LazyComponent></LazyComponent>

</Suspense>`

Example:
import React, { Suspense } from ‘react’;
const LazyComponent = React.lazy(() => import(‘./LazyComponent’));

function App() {
return (
<Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense>
);
}

17
Q

What are Custom Hooks in React and how do you create one?

A

Custom Hooks are a mechanism to reuse stateful logic between React components. They are not a feature of React itself, but a pattern that emerges from the Hooks API. Custom Hooks are functions that start with “use” and can call other Hooks.

Syntax:
function useMyCustomHook(arg1, arg2) {
// Hook logic here
return someValue;
}

Example:
import { useState, useEffect } from ‘react’;

function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, [url]);

return { data, loading };
}

// Usage
const { data, loading } = useFetch(‘https://api.example.com/data’);

Custom Hooks allow you to abstract and reuse complex logic, making your components cleaner and easier to understand.

18
Q

What are React Portals and how do you use them?

A

React Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This is useful for rendering components that are visually “broken out” from their container, like modals, tooltips, or notifications.

Syntax:
ReactDOM.createPortal(child, container)
child: The React element you want to render.
container: The DOM element you want to render the child into.

Example:
import React from ‘react’;
import ReactDOM from ‘react-dom’;

function Modal({ children }) {
const modalRoot = document.getElementById(‘modal-root’);
return ReactDOM.createPortal( children, modalRoot );
}

// Usage
function App() {
return (
<div>
<h1>Hello, World!</h1>
<Modal>
<div className="modal">
This is a modal.
</div>
</Modal>
</div>
);
}

In this example, the Modal component renders its children into a DOM node (modal-root) that is outside of the App component’s DOM hierarchy.

19
Q

What are Error Boundaries in React and how do you use them?

A

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.

Key Methods:

static getDerivedStateFromError(error): Updates state so the next render will show the fallback UI.

componentDidCatch(error, info): You can also log the error to an error reporting service.

Example:
`Boundary extends React.Component {
state = { hasError: false };

static getDerivedStateFromError(error) {
return { hasError: true };
}

render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}`

// Usage
function App() {
return (
<>
<h1>Hello World</h1>
<ErrorBoundary fallback={<h1>There was an error</h1>}>
<Buggy></Buggy>
</ErrorBoundary>
</>
);
}

function Buggy() {
throw new Error(‘error’);
return <h1>Buggy</h1>;
}

In this example, if the Buggy component throws an error, the ErrorBoundary will catch it and render the fallback UI (<h1>There was an error</h1>).