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 React with Vite?

A
npm create vite@latest my-react-app --template react

Than cd into the folder

npm install

To start the development server:

npm run dev
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]);
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

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

A
<ComponentName propName={functionName} />
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

Describe the typical hierarchy of components in a React application.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

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

Where should the useState or useEffect hook be used?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>
~~~

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

How should style names be written in React?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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’ };
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>
~~~

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

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

A

htmlFor attribute

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

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

How to bind the input field to the state value?

A

With the value attribute in form inputs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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} />
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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];
    })
  }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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>
168
Q

How to import css modules and use the styles in react?

A

First import the styles and than apply it with className={styles.class}

import styles from './HomePage.module.css'

export default function Page() {
  return <div className={styles.intro}>Framework Supermarket</div>;
}
169
Q

How to bootstrap a default Next.js app?

A

npx create next app my-app

170
Q

What is the purpose of the App Router in Next.js?

A

The App Router defines and structures an application’s routes and their UIs, and is created using a folder named app at the project’s root level.

171
Q

How are folders and reserved files used in the Next.js App Router?

A

Folders define path segments, and reserved files like page.tsx define the UI for those segments.

172
Q

How do you create nested routes in Next.js?

A

Nested routes are created by nesting folders within the app directory.

173
Q

What Next.js tools provide SPA-like navigation?

A

The useRouter() hook and <link></link> component provide SPA-like navigation in Next.js.

174
Q

What does the useRouter() hook return, and what can you do with it?

A

It returns a router object with methods like push(path), back(), and forward() for navigation.

175
Q

What is the role of the page.tsx file in Next.js?

A

It defines a unique UI for its containing path segment and must default export a React component.

176
Q

What are layout.tsx and template.tsx files used for in Next.js?

A

Both are used to create shared UIs, but layout.tsx persists across navigations while template.tsx re-instantiates.

177
Q

What is a dynamic segment in Next.js, and how is it created?

A

A dynamic segment is created by wrapping a folder name in square brackets, like /app/users/[userId]. It receives dynamic data via a params prop.

178
Q

How do you create a catch-all dynamic segment in Next.js?

A

A catch-all dynamic segment is created by prefixing the dynamic segment with ellipses, e.g., /app/articles/[…articleIds].

179
Q

What are some of the special reserved files in Next.js and their purposes?

A

Reserved files include:

  • layout.tsx: Defines a shared UI.
  • template.tsx: Defines a shared UI.
  • error.tsx: Defines an ErrorBoundary UI.
  • loading.tsx: Defines a Suspense fallback UI.
  • not-found.tsx: Handles unknown segments.
180
Q

How do layout.tsx and page.tsx work together in next.js?

A

Next.js applies the layout automatically to all pages in the same directory and its subdirectories.

The content of each page is automatically passed as children prop to the layout component.

export default function RootLayout( {children} ) {
  return(
    <>
      <UrlBar/>
      <Nav/>
      {children} // the content of the pages
    </>
  )
}
181
Q

How do you create a new route in next.js?

A

By adding a new folder nad inside this new folder creating a page.tsx with all the content of the new route.

182
Q

How can you prevent page reloads in next.js when clicking links?

A

By using Link instead of a tags and importing Link beforehand.

import Link from 'next/link'

<Link href={`/users/${userId}`} >
          User: {userId}
</Link>
183
Q

How can you indicate which Nav Links are active in next.js?

A

By importing:

import { usePathname } from 'next/navigation';

And than check each element with the current path

const pathname = usePathname();

return (
     <li className={pathname === '/' ? styles.active : ''}>
          <Button label="Home" href="/" />
        </li>
)
184
Q

What is the useRouter hook in Next.js?

A

The useRouter hook gives access to the Next.js router object, allowing you to inspect the current route or programmatically control navigation between pages.

185
Q

How do you import and use the useRouter hook in a Next.js component?

A
import { useRouter } from 'next/router';

const MyComponent = () => {
  const router = useRouter();  // Access the router object

  return (
    <div>
      <p>Current path: {router.pathname}</p>  // Access route info
    </div>
  );
};
186
Q

What does the router.push method do in Next.js?

A

router.push allows you to navigate to a different URL in Next.js without a full-page reload. It changes the route and updates the browser’s address bar, pushing the new URL onto the history stack.

187
Q

What is the syntax for router.push in Next.js?

A
router.push(url, as, options);
  • url: The path to navigate to (string or object).
  • as (optional): The URL to show in the address bar (if different from url).
  • options (optional): An object with additional options like shallow.
188
Q

How do you use router.push to navigate to /about on button click?

A
import { useRouter } from 'next/router';

const MyComponent = () => {
  const router = useRouter();

  const handleNavigation = () => {
    router.push('/about');  // Navigates to the '/about' page
  };

  return (
    <div>
      <button onClick={handleNavigation}>Go to About Page</button>
    </div>
  );
};
189
Q

How can you use router.push to navigate to a dynamic route in Next.js?

A
router.push({
  pathname: '/product/[id]',  // Dynamic path
  query: { id: '123' }        // Passing query params (id = 123)
});

This would navigate to /product/123.

190
Q

In React, how would you check if a userName already exists in an array of contacts and update a state accordingly, only when userName or contacts changes?

A
useEffect(() => {
    setIsDuplicate(contacts.some(contact => contact.userName === userName));
}, [userName, contacts]);
  • contacts.some() checks if any contact’s userName matches the given userName.
  • setIsDuplicate updates the state with true if a match is found, otherwise false.
  • This hook runs whenever userName or contacts changes.
191
Q

In React, how do you update the name state with each input change for a text input field?

A
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />

Explanation:
- The onChange handler captures the event object e.
- e.target.value extracts the user’s input from the text field.
- setName(e.target.value) updates the name state with the new value.

192
Q

How can you capture the input value from a form in React?

A

You can capture the input value by using a controlled component. This involves setting the input’s value to a state variable and updating that state with the onChange event handler.

<input 
  type="text" 
  value={inputValue} 
  onChange={(event) => setInputValue(event.target.value)} 
/>
193
Q

How do you create a new item object when the form is submitted?

A

You create a new item object by assigning the input value to a property (e.g., name) and generating a unique identifier (e.g., id) using Date.now() or a UUID.

const newItem = {
  name: inputValue,
  id: Date.now(),
};
194
Q

What is the purpose of mapping over the items array to render a list?

A

Mapping over the items array allows you to dynamically render a list of items in the UI. Each item in the array is transformed into a corresponding list item element.

<ul>
  {items.map(item => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>
195
Q

How can you validate the input before adding a new item in React?

A

You can implement input validation by checking if the input value is empty or meets specific criteria before creating the new item and updating the state.

if (!inputValue.trim()) {
  alert("Input cannot be empty");
  return;
}
196
Q

What is the difference between controlled and uncontrolled components in React?

A

Controlled components are components where React controls the form data via state, while uncontrolled components store form data in the DOM. Controlled components provide better control and predictability.

<input value={inputValue} onChange={handleChange} />
197
Q

How do you style a React component using global CSS?

A

Import the CSS file directly into the component:

import './styles.css';

Apply classes using the className attribute in JSX:

<div className="container"></div>
198
Q

How do you scoped style a React component using CSS?

A

Import the CSS file as a module:

import styles from './styles.module.css';

Apply classes using styles.className:

<div className={styles.container}></div>
199
Q

How do you toggle a class based on a condition in a JSX element?

A

Use a conditional expression:

className={condition ? 'className' : ''}
200
Q

What is the purpose of the handleChecked function in a checkbox component?

A

It toggles the checked state of a specific item in the list based on its id.
Code Snippet:

const handleChecked = (id) => {
  setItems(prevItems => 
    prevItems.map(item => 
      item.id === id ? { ...item, checked: !item.checked } : item
    )
  );
};
201
Q

How do you update the state of an array in React without mutating the original array?

A

Use the map() method to create a new array, modifying only the relevant item.

setItems(prevItems => 
  prevItems.map(item => 
    item.id === id ? { ...item, checked: !item.checked } : item
  )
);
202
Q

What is the difference between the checked attribute and the onChange event in a checkbox?

A

The checked attribute sets the checkbox’s state, while onChange triggers an action when the state changes.

<input 
  type='checkbox' 
  checked={item.checked} 
  onChange={() => handleChecked(item.id)} 
/>
203
Q

What should the initial state of an item include when adding it to a list?

A

Each item should have properties like name, id, and checked (initialized to false).

const newItem = {
  name: item.value,
  id: Date.now(),
  checked: false
};
204
Q

How can you implement a delete button for a todo list e.g.?

A

By using useState to set the state, with the current item filtered out with .filter

<button className='delete' onClick={() => setItems(prevItems => prevItems.filter(i => i.id!== item.id))}>
                  ✖
                </button>
205
Q

How can you update state in React when the user types into an input field?

A

Use the onChange event handler to update the corresponding state for each input.

<input 
  type="text" 
  value={stateValue} 
  onChange={(e) => setStateValue(e.target.value)} 
/>
206
Q

How do you clear form fields after a successful submission in React?

A

Reset the state values to empty strings in the handleSubmit function after successfully adding the data.

setUserName("");
setPhoneNumber("");
setEmail("");
207
Q

How can you reset or update error messages dynamically when a user types in a field?

A

Update the setErrorMessage state within the onChange handler based on the current input value.

onChange={(e) => {
  const newName = e.target.value;
  setName(newName);
  if (newName && !isDuplicate) {
    setErrorMessage("");
  } else if (isDuplicate) {
    setErrorMessage("Duplicate Name");
  }
}}
208
Q

How do you handle duplicate name checks in a contact form using useEffect?

A

Use useEffect to check if the entered name already exists in the contact list and update the isDuplicate state accordingly.

useEffect(() => {
  setIsDuplicate(contacts.some(contact => contact.userName === userName));
}, [userName, contacts]);
209
Q

How would you render an object’s values in a list of <p> tags using React?

A
{Object.values(obj).map((value, index) => (
  <p key={index}>{value}</p>
))}
210
Q

What is .map() commonly used for in React?

A

In React, .map() is commonly used to iterate over arrays and render elements for each item in the array.

const numbers = [1, 2, 3];
return (
  <div>
    {numbers.map((number) => (
      <p key={number}>{number}</p>
    ))}
  </div>
);
211
Q

How can you remove immutable an item at a given index?

A

With the spreadoperator and two slice methods:

export const removeItemAtIndex = (list, index) => {
 return [...list.slice(0,index), ...list.slice(index+1)] 
};
212
Q

How do you get the current state in redux?

A
store.getState();
213
Q

You have three reducers(aReducer, bReducer, cReducer). How do you combine these and create finally a store?

A

In store.js import all the reducers and createStore and combineReducers like this:

import { createStore, combineReducers } from 'redux';
import { aReducer } from '../features/a/aSlice.js;

Then create a bundled reducers Object:

const reducers = {
    aSlice: aReducer,
    etc. ...

Than create the rootReducer

const rootReducer = combineReducers(reducers);

and from there create and export the store:

export const store = createStore(rootReducer);
214
Q

Which data do you need to pass as props after importing the redux store into your index.js?

A

The current state of the store and dispatch to the <App></App>:

<App 
      state={store.getState()}
      dispatch={store.dispatch}
    />
215
Q

Where do you import the store in redux?

A

In the entry point. The index.js:

import { store } from './app/store.js'
216
Q

How do you get the current state of the store in redux?

A
store.getState()
217
Q

How do you listen to changes of the state of the store in redux in your index.js?

A
store.subscribe(render);

render is the function that renders the whole app component.

218
Q

How do you dispatch an action in redux?

A

By calling dispatch() with the action and it’s passed values:

dispatch(action(propA, propB))
219
Q

How do you import the configureStore from Redux Toolki?

A
import { configureStore } from '@reduxjs/toolkit'
220
Q

How do you setup an store in redux toolkit?

A
export configureStore({
 reducer: {
   todos: todosReducer,
   filters: filtersReducer
 }
})
221
Q

What is createSlice in Redux Toolkit?

A

createSlice is a function that simplifies creating Redux logic by combining reducer, actions, and initialState in one place.

222
Q

What is the purpose of the name field in createSlice?

A

name is a prefix for action types generated by the slice, helping identify the actions of this specific slice.

223
Q

What are reducers in createSlice?

A

reducers is an object where each key is an action, and its value is a reducer function that updates the state based on the action.

224
Q

Write a sample createSlice configuration for a counter with actions to increment and decrement.

A
const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; }
  }
});
225
Q

How can you access actions generated by createSlice?

A

Actions can be accessed via destructuring:

export const { increment, decrement } = counterSlice.actions;
226
Q

What is the purpose of the “main” field in package.json?

A

It specifies the entry point of your application, usually a file like index.js.

227
Q

What command is used to install a development dependency?

A

npm install [package-name] –save-dev

228
Q

What does the caret (^) symbol mean in dependency versions?

A

The caret (^) allows updates for the latest minor or patch version while maintaining the major version.

229
Q

What does the tilde () symbol mean in dependency versions?

A

The tilde () only allows updates for the latest patch version while maintaining the major and minor versions.

230
Q

In Redux/toolkit createAsyncThunk() accepts two arguments. In order, they are?

A

createAsyncThunk‘s arguments are an action type string and an asynchronous thunk function.

231
Q

What is a thunk in redux?

A

A function returned by another function

232
Q

Which two programming concepts does Redux Toolkit use internally for createAsyncThunk()?

A

Middleware and thunks

233
Q

What is the purpose of middleware in Redux?

A

Redux middleware extends the store’s abilities and lets you write asynchronous logic that can interact with the store. Middleware is added to the store either through createStore() or configureStore().

234
Q
A