Things to remeber in React Flashcards

1
Q

What file should you create to signal that a project uses Prettier?

A

Create a .prettierrc file with {} for default configuration.

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

How do you integrate Prettier with Visual Studio Code?

A

Install the Prettier extension and set prettier.requireConfig to true and editor.formatOnSave to true.

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

How can you configure ESLint for a project?

A

ESLint is configured using a .eslintrc file where you define rules, settings, and plugin configurations.

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

How can you install ESLint in a project?

A

Install ESLint using ‘npm install –save-dev eslint’

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

What file does ESLint use to manage its configuration?

A

ESLint uses configuration files like .eslintrc.json, .eslintrc.js, or .eslintrc.yml for settings.

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

Which common files and directories should be added to a .gitignore file in a Node.js project?

A
  • node_modules
  • dist/
  • .env
  • .DS_Store
  • coverage/
  • .vscode/
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why should node_modules/ be included in .gitignore?

A

The node_modules/ directory contains installed dependencies and can be recreated with npm install, so it should not be committed to the repository.

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

How do you install Vite and the React plugin for a project?

A

Use the command ‘npm install -D vite@3.1.4 @vitejs/plugin-react@2.1.0’ to install Vite and the React plugin.

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

What modification is needed in index.html when using Vite?

A

Replace the unpkg React script tags with

, indicating that modern modules are being used.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Where should you place the Vite configuration file, and what does it contain?

A

Place vite.config.js in the root of your project. It should contain:
~~~
import { defineConfig } from “vite”;
import react from “@vitejs/plugin-react”;

export default defineConfig({
plugins: [react()],
root: “src”,
});
~~~

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

What does the root property in vite.config.js specify?

A

The root property specifies the directory where Vite will look for index.html. Typically, it’s set to “src” if index.html is located there.

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

How do you install React and ReactDOM for a Vite project?

A

Run npm install react@18.2.0 react-dom@18.2.0 to add React and ReactDOM as production dependencies.

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

What scripts should be added to package.json for using Vite?

A
"scripts": {
  "dev": "vite",
  "build": "vite build",
  "preview": "vite preview"
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What do the dev, build, and preview scripts do in a Vite project?

A
  • dev starts the development server.
  • build generates optimized static files for production.
  • preview lets you preview the production build locally.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you pass props to a React component in JSX?

A

Props are passed as attributes in JSX. For example:

<Pet name="Luna" animal="dog" breed="Havanese" />
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you configure ESLint to recognize React version automatically?

A

Add the following to the .eslintrc.json file:

"settings": {
  "react": {
    "version": "detect"
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a React hook?

A

A function that allows you to use state and other React features in functional components.

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

What is the purpose of useState in React?

A

useState provides a state variable and a function to update it, allowing for dynamic rendering.

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

What is the purpose of the htmlFor attribute in JSX?

A

htmlFor is used instead of for because for is a reserved word in JavaScript.

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

How do you handle form inputs in React?

A

Use controlled components with useState for each input’s value and change handlers to update state.

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

What is useEffect in React?

A

useEffect is a React hook that allows you to perform side effects in functional components, like fetching data after a component renders.

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

When does the useEffect hook run?

A

The useEffect hook runs after the initial render of a component. You can control when it re-runs by specifying dependencies.

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

How do you prevent useEffect from running on every render?

A

Provide an empty array [] as the second argument to useEffect to ensure it only runs once, after the initial render.

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

What is a custom hook in React?

A

A custom hook is a reusable function in React that leverages other hooks (e.g., useState, useEffect) to encapsulate and manage logic, making it reusable across multiple components.

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

How does useState Hook work in React?

A

useState is a Hook that allows you to add state to function components, providing a way to store and update state within the component.

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

What are the three main phases of a React component’s lifecycle?

A

The three main phases are mounting, updating, and unmounting.

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

How does the useState hook work in React?

A

The useState hook allows you to add state to a functional component. It returns an array with the current state and a function to update it.

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

What is the purpose of the useEffect hook in React?

A

The useEffect hook is used to handle side effects in React components, such as data fetching, subscriptions, or manually updating the DOM.

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

Why is the key prop important when rendering lists in React?

A

The key prop helps React identify which items in a list have changed, ensuring efficient updates and preventing unnecessary re-renders.

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

How can you persist state in React using local storage?

A

Use the useEffect hook to save the component’s state to local storage and retrieve it on component mount, ensuring data persists across page reloads.

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

What is the difference between state and props in React?

A

State is used to manage data within a component, while props are used to pass data from one component to another.

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

What does const [a = aDefault] = array; do?

A

Assigns aDefault to a if a is undefined in the array.

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

What is the purpose of the …rest syntax in destructuring?

A

To collect the remaining elements or properties into a new array or object.

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

How do you destructure an array with a rest property?

A

const [first, …rest] = array;

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

How can you swap two variables using destructuring?

A

[a, b] = [b, a];

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

What is required when destructuring an object in an assignment pattern?

A

Parentheses around the assignment. Example: ({ a, b } = obj);

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

Can you use default values in object destructuring?

A

Yes, e.g., const { a = 10 } = obj;

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

How do you ignore values when destructuring an array?

A

Use commas to skip values, e.g., const [, , b] = [1, 2, 3];

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

Can you destructure values returned from a function?

A

Yes, e.g., const [a, b] = f();

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

Can you destructure iterables other than arrays?

A

Yes, e.g., const [a, b] = new Map([[1, 2], [3, 4]]);

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

How does the && operator work in JSX conditional rendering?

A

If the condition on the left of && is true, the JSX on the right will be rendered. If false, it will be ignored.

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

How are event listeners specified in JSX?

A

Event listeners in JSX are attributes written in camelCase (e.g., onClick). Their value should be a function, which can be declared inline or as a variable.

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

When should you use React Fragments in JSX?

A

Use React Fragments (<></>) to group multiple elements without adding extra nodes to the DOM.

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

What is an example of exporting a React component?

A
export default MyComponent;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What is an example of importing a React component?

A
import MyComponent from './MyComponent';
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

How can React components be shared between different files?

A

```// Exporting a component
export default MyComponent;

// Importing a component
import MyComponent from ‘./MyComponent’;
~~~

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

What two methods are required to render a React component to the DOM?

A

.createRoot() to specify a root container and .render() to render the component.

```import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
import App from ‘./App’;

// Create a root container
const root = createRoot(document.getElementById(‘app’));

// Render the component to the root container
root.render(<App></App>)
~~~

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

In a JSX, use onClick event listeners to call the setColor() state setter function with a color when the user clicks on each that button.

<button>
        Aquamarine
      </button>
A
<button onClick={() => setColor('Aquamarine')}>
        Aquamarine
      </button>

The onClick attribute is given an inline arrow function () => setColor(‘Aquamarine’). This function is executed when the button is clicked, and it calls setColor with the argument ‘Aquamarine’.

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

What is the syntax for initialzing a useState()?

A

const [isSomething, setSomething] = useState(optionalDefaultValue);

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

How can you simplify this React event handler using object destructuring?

```const handleChange = (event) => {
const newEmail = event.target.value;
setEmail(newEmail);
}
~~~

A

```const handleChange = ({ target }) => setEmail(target.value);
~~~

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

How can you add a new item?

```const [cart, setCart] = useState([]);

const addItem = (item) => {
???
};```

A
setCart(prevCart => {
      return [item, ...prevCart];
    })

prevCart is basically the isState of the cart. …prevCart adds it to the item.

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

What is the basic syntax of useState?

A

const [state, setState] = useState(initialState);

- state: current state value
- setState: function to update the state    -  initialState: initial value of the state
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

How to copy over a previous state in React. So keep Data when user enters new data?

A

Use the spread syntax on collections of dynamic data to copy the previous state into the next state like so:

setArrayState((prev) => [ ...prev ])

and
setObjectState((prev) => ({ ...prev }))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

How do you add an event listener in a useEffect hook?

A

Use

document.addEventListener('event', handler)
inside the useEffect hook.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

How do you clean up an event listener in a useEffect hook?

A

Return a cleanup function from the useEffect hook that calls

return () => {
document.removeEventListener('event', handler);
}
    }, []);
.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What does the empty dependency array [] in useEffect do?

A

It ensures the effect runs only once when the component mounts.

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

How do you define an event handler function in a React component?

A

Define the function as a constant, e.g.,

const increment = () => { /* logic */ };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

How do you pass a reference to an event handler in addEventListener?

A

Pass the function name without parentheses, e.g.,

document.addEventListener('mousedown', increment)
.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Why is it important to use the same function reference in addEventListener and removeEventListener?

A

To ensure the event listener is correctly added and removed, preventing memory leaks and unexpected behavior.

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

How do you run an effect only when a component mounts?

A

Pass an empty array [] as the second argument to useEffect().

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

What does JSON.stringify(response, ‘’, 2) do?

A

Converts the response object to a readable string with indentation for easy viewing.

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

How do you fetch data in a useEffect hook?

A

Use an async function inside useEffect and call it:

```useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const data = await response.json();
setState(data);
}
fetchData();
}, [dependencies]);
~~~

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

Where should you call unsubscribe() in a function component to ensure it is executed before the component is removed from the DOM?

A

In a cleanup function, returned by the first argument of the Effect Hook.

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

How do you correctly set up and clean up an event listener for ‘mousedown’ events in a function component?

A

```useEffect(() => {
document.addEventListener(‘mousedown’, increment);
return () => {
document.removeEventListener(‘mousedown’, increment);
};
}, []);
~~~

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

Why should we use Hooks with function components?

A

Hooks add state to function components.

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

How do you fetch and render data from a server in a function component?

A

```function FetchAndViewData({ endpoint }) {
const [data, setData] = useState(null);
useEffect(() => {
get(endpoint).then((response) => setData(response.data));
}, [endpoint]);
return <div>{JSON.stringify(data, ‘’, 2)}</div>;
}
~~~

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

Which event handler best adds a clicked item to an array state variable?

A
const addItem = ({ target }) => {
  setItems((prev) => [target.value, ...prev]);
};
68
Q

How do you pass a function as a prop in React?

A
<ComponentName propName={functionName} />
69
Q

How do you calculate the remaining time until an event in JavaScript?

A

Subtract the current time from the event time: eventTime - Date.now()

70
Q

What does props.addThought(thought) do in a child component?

A

It calls the addThought function passed from the parent to add a new thought.

71
Q

How do you filter out an item from an array in React?

A

```const handleRemoveItem = (ItemToRemove) => {
// Here, prevTracks is automatically provided by React
setItemlist(prevItems =>
prevItems.filter(item => item !== ItemToRemove)
);
};
~~~

  • prevTracks: This is the current state of playlistTracks before the update.
  • filter: We filter out the trackToRemove, and the remaining tracks form the new state.
  • setPlaylistTracks: Updates the state with the filtered array.

Key Points

  • prevTracks is provided by React and represents the previous state.
  • This method ensures that your state updates are always based on the latest state, which is crucial in asynchronous environments like React.
72
Q

Describe the typical hierarchy of components in a React application.

A

index.js -> App.js (root) -> Container Component -> Presentational Component.

73
Q

How are props used in React components?

A

Props are passed as an object to components and can be destructured for easier access.

74
Q

Where should the useState or useEffect hook be used?

A

The useState hook should be used in container components to manage state.

75
Q

How does the rendering flow work in a React application?

A

The root component renders container components, which in turn render presentational components, forming a nested structure.

76
Q

What is a necessary part of any “stateful” component?

A

An initialization of state using the useState hook because it establishes the initial state value and enables state management within the component efficiently.

77
Q

How do you apply inline styles in React?

A

Use the style attribute with an object literal: <h1 style={{color: “red”}}>Hello, World!</h1>

78
Q

How do you use an object variable for styles in React?

A

Define a style object and pass it to the style attribute:
~~~
const myStyle = { color: “red” };
<h1 style={myStyle}>Hello, World!</h1>
~~~

79
Q

How should style names be written in React?

A

Style names must be in camelCase, e.g., background-color becomes backgroundColor.

80
Q

How do you import a CSS module in a React component?

A

Import the module and use the styles object:
~~~
import styles from ‘./styles.module.css’;
<div className={styles.className}></div>

~~~

81
Q

How do you define an object variable for styling in React?

A

Define it above the component:
~~~
const styleObj = { display: ‘flex’, marginBottom: ‘20px’ };
~~~

82
Q

How do you apply an object variable for styling in React?

A

Use the style attribute with the object variable:

<div style={styleObj}>Content</div>
83
Q

How do you apply a CSS module class in React?

A

Use the className attribute with the imported styles object:
~~~
<div className={styles.className}>Content</div>
~~~

84
Q

What is the syntax to apply multiple styles in a React component?

A

Use a JavaScript object with multiple properties:
~~~
<div style={{ fontSize: 20, color: ‘red’ }}>Text</div>
~~~

85
Q

What attribute is used to link a label to an input field in React?

A

htmlFor attribute

86
Q

How do you handle radio button inputs in React?

A

By using the name attribute to group them and onChange to update the state.

87
Q

How to bind the input field to the state value?

A

With the value attribute in form inputs

88
Q

What is the shorthand for handling typing and deleting events in React inputs?

A

```<input onChange={(e) => setName(e.target.value)}
value={name} />
~~~

89
Q

How to prevent adding Items to a list where item is already present in React?

A

With .some:

const handleAddToItemlist = (item) => {
    setItemlist(prevItems => {
      const isItemAlreadyAdded = prevItems.some (
        (prevItem) => prevItem === item
      );

      if (isItemAlreadyAdded) {
        return prevItems;
      }

      return [...prevItems, item];
    })
  }
90
Q

What is useEffect used for in React?

A

useEffect is used to manage side effects in React functional components, such as data fetching, subscriptions, and manual DOM manipulation.

91
Q

When does useEffect run in a React component?

A

useEffect runs after the component renders (i.e., after the JSX is returned and the DOM is updated).

92
Q

How do you control when useEffect runs?

A

By passing a dependency array as the second argument to useEffect. The effect only runs when the dependencies in the array change.

93
Q

What happens if you pass an empty array ([]) to useEffect?

A

The effect runs only once, after the initial render, and does not run on subsequent renders.

94
Q

What is the

<Outlet />
component in React Router?
A

<Outlet></Outlet>

is used in react-router-dom to render the content of child routes within a parent route. It acts as a placeholder for nested routes to display their components inside the parent route’s layout.

95
Q

What does useParams return if you visit /users/123 in a route defined as /users/:id?

A

It returns { id: “123” }, where the key id matches the dynamic part of the URL.

96
Q

What is the purpose of the

<Link>
component in react-router-dom?
A

The

<Link>
component creates navigational links that change routes without causing a full page reload, using client-side navigation for faster performance.
97
Q

What is the difference between

<Link>
and
<NavLink>
?
A
<Link>
is for navigation between routes, while
<NavLink>
adds styling or classes to the link when it matches the current route, making it useful for active state highlighting.
98
Q

How do you define a loader for a route in React Router?

A

A loader is defined in the route configuration using the loader property. The loader function fetches data before the route component renders, and the data is accessed using useLoaderData().

99
Q

What is useLoaderData() used for?

A

useLoaderData() is a hook used to access the data fetched by the loader associated with the current route. It allows you to access the preloaded data in the component.

100
Q

What is <Form> in react-router-dom used for?

A

<form> is a declarative component for handling form submissions. It integrates with the router, allowing form data to be submitted to an action handler without manually writing onSubmit event handlers.
</form>

101
Q

What does the action function do in React Router?

A

The action function processes form submissions or data-mutation requests. It is defined in the route configuration and is triggered automatically when a form is submitted with the <Form> component.

102
Q

How do you access form data inside an action function?

A

You can access form data in an action by using request.formData() to retrieve the form values from the submitted data.

103
Q

What is redirect() in React Router’s action?

A

redirect() is used inside an action to navigate the user to a different route after a successful form submission or data mutation. Example: return redirect(“/success”)

104
Q

What happens when a form is submitted using

<Form method="post">
in React Router?
A

When the form is submitted, React Router automatically sends the form data to the action function associated with the current route, where the form can be processed.

105
Q

What are the possible values of navigation.state from useNavigation?

A

The possible values are:

  • “idle”: No navigation is happening (default).
  • “submitting”: A form is currently being submitted.
  • “loading”: A route is being loaded (e.g., navigating to a new page or after form submission).
106
Q

How can you detect if a form is currently being submitted using useNavigation?

A

You can check if navigation.state === “submitting”. If true, it indicates that a form is currently being submitted, and you can show a loading spinner or disable a submit button.

107
Q

How do you use useNavigation to display a loading spinner when navigating between routes?

A

You can check if navigation.state === “loading”. When this condition is true, you can display a loading spinner or message until the new route finishes loading.

108
Q

What is the formData property of the navigation object in useNavigation?

A

The formData property contains the data being submitted in the form when the navigation.state is “submitting”. You can use this to display information about the form submission process.

109
Q

What does navigation.formMethod indicate when using useNavigation?

A

navigation.formMethod indicates the method (POST, GET, etc.) used for submitting the form. It is useful for customizing behavior based on the type of form submission.

110
Q

How do you disable a submit button while a form is being submitted with useNavigation?

A

You can conditionally disable the button using:

<button type="submit" disabled={navigation.state === "submitting"}>
  Submit
</button>
111
Q

How can you display different messages based on whether the app is submitting a form or loading a new route using useNavigation?

A

You can use:

if (navigation.state === "submitting") {
  return <p>Submitting form...</p>;
} else if (navigation.state === "loading") {
  return <p>Loading new route...</p>;
}
112
Q

What is the default state of navigation.state when there is no active navigation or form submission?

A

The default state is “idle”, meaning no navigation or form submission is currently happening.

113
Q

What is the purpose of redirect() in React Router?

A
  • redirect() is used to programmatically navigate the user to a different route.
  • It can be used after completing an action like form submission, data update, or deletion.
  • It changes the URL without requiring a full page reload.
114
Q

What does params represent in an action function in React Router?

A
  • params is an object containing the dynamic parts of the route (like IDs).
  • It is passed to the loader or action functions to access route parameters.
  • Example: params.contactId for the route /contacts/:contactId.
115
Q

Explain the code for programmatically submitting a form using useSubmit.

const submit = useSubmit();

submit(formData, { method: "post", action: "/contacts/new" });
A
  • useSubmit is a hook that allows form submission programmatically without the need for a form element.
  • You can pass formData, specify the HTTP method, and provide the target route (action).
  • Useful for triggering submissions on events like button clicks.
116
Q

What are the different states in useFetcher?

A
  • “idle”: No active submission or data fetching.
  • “submitting”: Data is currently being submitted.
    “loading”: The response is being fetched after submission.
  • useFetcher helps manage these states for background operations like fetching data or submitting forms.
117
Q

What does this code do?

onChange={(event) => {
  const isFirstSearch = q == null;
  submit(event.currentTarget.form, {
    replace: !isFirstSearch,
  });
}}
A
  • Handles the onChange event of an input field.
  • submit() programmatically submits the form when the input changes.
  • If it’s the first search (q == null), replace is set to false, adding a new entry in the history. Otherwise, it replaces the history entry to prevent clutter.
118
Q

What is useLoaderData used for?

A
  • useLoaderData is a hook provided by React Router that retrieves the data loaded by the route’s loader.
  • It is often used to access data needed for rendering a component.
119
Q

What is the difference between useSubmit and useFetcher?

A
  • useSubmit: Allows you to programmatically submit a form or form data to a route and trigger the corresponding action.
  • useFetcher: Can be used to submit forms or fetch data without navigation. It’s decoupled from the URL or route navigation and is ideal for background operations.
120
Q

What does useNavigate do?

A
  • It returns the data loaded by the route’s loader function.
  • Used in a component to access and render the data fetched for that route, like const { contact } = useLoaderData();.
121
Q

What is the purpose of localforage.getItem(“contacts”) in this function?

let contacts = await localforage.getItem("contacts");
A
  • localforage.getItem(“contacts”) fetches the contacts array stored in the browser’s local storage using the localforage library.
  • It retrieves the data for client-side persistence without making network requests.
122
Q

Q: What does useFetcher.load() do?

A
  • useFetcher.load() programmatically triggers a data fetch from a URL or route loader.
  • It doesn’t change the page’s route but allows you to fetch additional data in the background, like loading contact details.
123
Q

How do you trigger a form submission with useFetcher without reloading the page?

A
fetcher.submit(formData, { method: "post", action: "/contacts/new" });
  • fetcher.submit() submits the form programmatically without reloading the page or changing the current route.
  • It can send form data and specify the method (post) and action (the route to submit to).
124
Q

How do you define a root route with a pathless route for error handling in object-based route configuration?

A
createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    errorElement: <ErrorPage />,
    children: [
      {
        errorElement: <ErrorPage />,
        children: [
          { path: "contacts/:contactId", element: <Contact /> },
        ],
      },
    ],
  },
]);
125
Q

How do you define a root route with a pathless route for error handling in JSX route configuration?

A
<Route path="/" element={<Root />} errorElement={<ErrorPage />}>
  <Route errorElement={<ErrorPage />}>
    <Route path="contacts/:contactId" element={<Contact />} />
  </Route>
</Route>
126
Q

How do you create a QueryClient instance?

A

You create a QueryClient using:

import { QueryClient } from 'react-query';

const queryClient = new QueryClient();
127
Q

How do you set up QueryClientProvider in your app?

A

You wrap your app with QueryClientProvider, passing the QueryClient instance like so:

<QueryClientProvider client={queryClient}>
  <App />
</QueryClientProvider>
128
Q

Which hook is for fetching and caching data, that automatically handles loading, error, and stale data states, and it caches the result for future use.

A

useQuery

129
Q

What are the key arguments of useQuery?

A

The two key arguments are:

  • Query key: A unique key (e.g., ‘myData’) that identifies the query.
  • Query function: A function that fetches the data (e.g., fetchData).
const { data, isLoading, error } = useQuery('myData', fetchData);
130
Q

What values does useQuery return?

A

useQuery returns several helpful values including:

  • data: The fetched data.
  • isLoading: Whether the data is still being fetched.
  • error: Any error encountered during the fetch.
  • isError, isSuccess, isStale, etc.
131
Q

How does React Query handle caching?

A

React Query caches query results and automatically serves them until they become stale. Cached data is reused across components, reducing unnecessary network requests.

132
Q

What does useMutation do in React Query?

A

useMutation is a hook for handling mutations (e.g., creating, updating, deleting data). It provides state management for loading, error, and success states but does not cache results like useQuery.

133
Q

How do you use useMutation in React Query?

A

ou pass a function to useMutation that performs a data-modifying request, such as a POST or PUT request:

const mutation = useMutation(newData => {
  return fetch('/api/data', {
    method: 'POST',
    body: JSON.stringify(newData),
  });
});
134
Q

What states does useMutation return?

A

useMutation returns:

  • mutate: Function to trigger the mutation.
  • isLoading: Mutation is in progress.
  • isError: Mutation failed.
  • isSuccess: Mutation succeeded.
135
Q

How does React Query handle background refetching?

A

React Query automatically refetches data in the background when the data becomes stale, the app gains focus, or the network reconnects, keeping the UI up-to-date.

136
Q

How do you handle errors in React Query?

A

React Query automatically provides error and isError states when using useQuery or useMutation. You can conditionally render error messages based on these states:

if (isError) return <p>Error occurred: {error.message}</p>;
137
Q

What are the two arguments passed to createPortal?

A
  1. The JSX you want to render (e.g., <div>Modal content</div>).
  2. The DOM element where you want to render it (e.g., document.getElementById(‘modal-root’)).
138
Q

Where should you create the DOM node for a modal in your HTML?

A

You should create a separate <div id="modal-root"></div> outside of your main React root (e.g., outside the #root element in public/index.html).

139
Q

In the Modal component, why do we use the useRef hook?

A

We use useRef to create a persistent reference to a newly created div that holds the modal content. This ref persists across renders and can be attached to the #modal-root.

140
Q

When should you call setShowModal(true) in your component?

A

Call setShowModal(true) when you want to open the modal (e.g., on a button click).

141
Q

What is the purpose of conditional rendering (showModal && <Modal></Modal>)?

A

Conditional rendering ensures that the Modal component is only rendered when showModal is true, keeping the modal hidden when it’s not needed.

142
Q

How does createPortal help in avoiding CSS layout issues when using modals?

A

Since createPortal renders the modal outside the parent component hierarchy, it avoids layout issues like clipping or z-index problems that could occur if the modal were rendered inside the parent.

143
Q

What is the purpose of using useEffect in the Modal component?

A

useEffect is used to append the modal div to the #modal-root when the component mounts and to remove it when the component unmounts (cleanup).

144
Q

Where should the modal content be rendered in the DOM?

A

The modal content should be rendered inside a dedicated DOM element like #modal-root, which is outside the main React DOM tree.

145
Q

Why is useState needed in the parent component that uses the Modal?

A

useState is needed to control whether the modal is shown or hidden. This state (e.g., showModal) is toggled to conditionally render the modal.

146
Q

How can you pass content to a modal using children?

A

```<Modal></Modal>

<div>Modal content goes here</div>

</Modal>
~~~

147
Q

How can you ensure the modal is closed when the user clicks a “Close” button?

A

You can ensure the modal closes by calling setShowModal(false) in the button’s onClick handler to hide the modal.

148
Q

How do you structure a useEffect hook in the modal component to append and remove the modal from the DOM?

A

```useEffect(() => {
const modalRoot = document.getElementById(‘modal-root’);
modalRoot.appendChild(elRef.current);

return () => {
modalRoot.removeChild(elRef.current);
};
}, []);
~~~

This hook ensures that the modal div is added to the #modal-root when the modal mounts, and cleaned up when it unmounts.

149
Q

How would you describe a function component?

A

A function component in React acts like a factory that produces new React components based on a blueprint, which is why the correct answer highlights the creation aspect, unlike the idea of dividing components mentioned in the incorrect response.

150
Q

The following code is supposed to return an <h1> with 100 as the content, but it won’t work for some reason. What must be changed in order to get 100 to be returned?

import React from 'react';

function FavoriteNumber() {
  const fave = 100;
  return <h1>fave</h1>;
}
A

In the return statement, wrap fave in curly braces.

return <h1>{fave}</h1>;
151
Q

Which of the following answers is the correct way to get <img></img> to render with fuzzyFox‘s properties?

import React from 'react';

const fuzzyFox = {
  src: 'http://some.url',
  alt: 'Fuzzy Fox'
};

function FuzzyFox() {
  return (
    <div>
      <h1>Friendly Fuzzy Fox</h1>
      <img />
    </div>
  );
}
A
<img
  src={fuzzyFox.src}
  alt={fuzzyFox.alt}
/>
152
Q

Complete the following code snippet so that the parent component passes “Hello from parent!” to the child component.

function ParentComponent() {
  return (
    <div>
      <ChildComponent 
***
=
***
 />
    </div>
  );
}

function ChildComponent(
***
) {
  return <p>
***
</p>;
}
A

The correct answer is props, {props.message} because in React, data is passed from parent to child components using props.

function ParentComponent() {
  return (
    <div>
      <ChildComponent 
**message**
=
**"Hello from parent!"**
 />
    </div>
  );
}

function ChildComponent(
**props**
) {
  return <p>
**{props.message}**
</p>;
}
153
Q

In React, what happens if there are no props passed to a component?

A

The component will use default values for any missing props.

154
Q

Which import statement allows a function component to use the State and Effect Hooks to generate dynamic JSX?

A

´´´
import React, { useEffect, useState } from ‘react’
´´´

155
Q

Why should we use Hooks with function components?

A

Hooks add state to function components.

156
Q

How to install react router?

A

npm install react-router-dom

157
Q

How to import react router?

A
import { createBrowserRouter } from 'react-router-dom';

at top of the file.

158
Q

How to make RouterProvider available to our entire application?

A
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
const router = createBrowserRouter( /* application routes are defined here */ );

export default function App () {
  return (
    <RouterProvider router={ router } />
  );
}
159
Q

What is the purpose of the createRoutesFromElements utility in React Router?

A

It converts JSX route elements into route objects, which can then be used by createBrowserRouter.

160
Q

What two main props does a route element take in React Router?

A

A path prop that specifies when the route should render, and an element prop that specifies what should render when the path matches.

<Route path='/about' element={ <About/> } />
161
Q

How do you pass a non-empty array of routes to the router?

A

Import createBrowserRouter, createRoutesFromElements and Route.

Than initiallize router with create Browser Router and createRoutesFromElements:

const router = (createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={ <Root/> }>
      <Route path="/about" element={ <About/> } />
      <Route path="/profile" element={ <Profile/> } />
    </Route>
  )
));
162
Q

What alternatives to anchor tags does React Router offer and what do they do?

A

the Link and NavLink components, both of which can be imported from the react-router-dom package:

import { createBrowserRouter, createRoutesFromElement, Route, Link, NavLink } from 'react-router-dom';

They have a to prop that indicates the location to redirect the user to, similar to the anchor tag’s href attribute.
~~~

<link></link>

About</Link>

<NavLink>About</NavLink>

~~~
the default behavior of an anchor tag – refreshing when the page loads – will be disabled
When the URL path matches a NavLink component’s to prop, the link will automatically have an ‘active’ class applied to it.

163
Q

How can you navigate conditionally to a certain link?

A

First
~~~
import { Navigate } from ‘react-router-dom’;
~~~
Than in the function:
~~~
const UserProfile = ({ loggedIn }) => {
if (!loggedIn) {
return (
<Navigate></Navigate>
)
}

return (
// … user profile content here
)
}
~~~

164
Q

How to navigate imperatively with React Router?

A

First
~~~
import { useNavigate } from ‘react-router-dom’;
~~~
Than initialize:
~~~
const navigate = useNavigate()
~~~
Than e.g.:
~~~
return (
<button onClick={() => navigate(-1)}>
Go Back
</button>
)
~~~

165
Q

How do you retrieve the search Parameters with react route?

A

First:
~~~
import { useSearchParams } from ‘react-router-dom’;
~~~
Than we call it in the component function:
~~~
const [ searchParams, setSearchParams ] = useSearchParams();
~~~
Finally, to get the value of a specific query parameter, we pass in the name of the query parameter whose value we want to obtain, as a string (‘order’), to the queryParams.get() method.
~~~
const sortOrder = searchParams.get(‘order’);
console.log(sortOrder); // Prints “DESC”
~~~
The value (‘DESC’) is then stored in the variable order.

// Rendered when a user visits “/list?order=DESC”

166
Q

What if we want to navigate to a path and include query parameters? e.g. /list?order=ASC

A
import { useNavigate, createSearchParams } from 'react-router-dom';
// get navigate function
const navigate = useNavigate();

Define an object representing the query parameters we want and call it searchQueryParams.
~~~
const searchQueryParams = {
order: ‘ASC’
}
~~~
Pass searchQueryParams to createSearchParams which will transform it from an object to a query string form.
~~~
const searchQueryString = createSearchParams(searchQueryParams);
~~~
Call useNavigate and pass an object with pathname and search keys where pathname is a string indicating where to navigate to and search is a string indicating the query string to append to the path.
~~~
navigate({
pathname:’/list’,
search: ?${searchQueryString}
})
~~~

167
Q

How to show the active link in NavLink?

A

Using destructuring syntax and a template string which checks if isactive is true:

<NavLink to="/" 
className={ ({ isActive }) => `nav-link ${isActive ? 'nav-link-active' : ''}`}               
</NavLink>