Things to remeber in React Flashcards
What file should you create to signal that a project uses Prettier?
Create a .prettierrc file with {} for default configuration.
How do you integrate Prettier with Visual Studio Code?
Install the Prettier extension and set prettier.requireConfig to true and editor.formatOnSave to true.
How can you configure ESLint for a project?
ESLint is configured using a .eslintrc file where you define rules, settings, and plugin configurations.
How can you install ESLint in a project?
Install ESLint using ‘npm install –save-dev eslint’
What file does ESLint use to manage its configuration?
ESLint uses configuration files like .eslintrc.json, .eslintrc.js, or .eslintrc.yml for settings.
Which common files and directories should be added to a .gitignore file in a Node.js project?
- node_modules
- dist/
- .env
- .DS_Store
- coverage/
- .vscode/
Why should node_modules/ be included in .gitignore?
The node_modules/ directory contains installed dependencies and can be recreated with npm install, so it should not be committed to the repository.
How do you install Vite and the React plugin for a project?
Use the command ‘npm install -D vite@3.1.4 @vitejs/plugin-react@2.1.0’ to install Vite and the React plugin.
What modification is needed in index.html when using Vite?
Replace the unpkg React script tags with
, indicating that modern modules are being used.Where should you place the Vite configuration file, and what does it contain?
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”,
});
~~~
What does the root property in vite.config.js specify?
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 do you install React and ReactDOM for a Vite project?
Run npm install react@18.2.0 react-dom@18.2.0 to add React and ReactDOM as production dependencies.
What scripts should be added to package.json for using Vite?
"scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }
What do the dev, build, and preview scripts do in a Vite project?
- dev starts the development server.
- build generates optimized static files for production.
- preview lets you preview the production build locally.
How do you pass props to a React component in JSX?
Props are passed as attributes in JSX. For example:
<Pet name="Luna" animal="dog" breed="Havanese" />
How do you configure ESLint to recognize React version automatically?
Add the following to the .eslintrc.json file:
"settings": { "react": { "version": "detect" } }
What is a React hook?
A function that allows you to use state and other React features in functional components.
What is the purpose of useState in React?
useState provides a state variable and a function to update it, allowing for dynamic rendering.
What is the purpose of the htmlFor attribute in JSX?
htmlFor is used instead of for because for is a reserved word in JavaScript.
How do you handle form inputs in React?
Use controlled components with useState for each input’s value and change handlers to update state.
What is useEffect in React?
useEffect is a React hook that allows you to perform side effects in functional components, like fetching data after a component renders.
When does the useEffect hook run?
The useEffect hook runs after the initial render of a component. You can control when it re-runs by specifying dependencies.
How do you prevent useEffect from running on every render?
Provide an empty array [] as the second argument to useEffect to ensure it only runs once, after the initial render.
What is a custom hook in React?
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 does useState Hook work in React?
useState is a Hook that allows you to add state to function components, providing a way to store and update state within the component.
What are the three main phases of a React component’s lifecycle?
The three main phases are mounting, updating, and unmounting.
How does the useState hook work in React?
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.
What is the purpose of the useEffect hook in React?
The useEffect hook is used to handle side effects in React components, such as data fetching, subscriptions, or manually updating the DOM.
Why is the key prop important when rendering lists in React?
The key prop helps React identify which items in a list have changed, ensuring efficient updates and preventing unnecessary re-renders.
How can you persist state in React using local storage?
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.
What is the difference between state and props in React?
State is used to manage data within a component, while props are used to pass data from one component to another.
What does const [a = aDefault] = array; do?
Assigns aDefault to a if a is undefined in the array.
What is the purpose of the …rest syntax in destructuring?
To collect the remaining elements or properties into a new array or object.
How do you destructure an array with a rest property?
const [first, …rest] = array;
How can you swap two variables using destructuring?
[a, b] = [b, a];
What is required when destructuring an object in an assignment pattern?
Parentheses around the assignment. Example: ({ a, b } = obj);
Can you use default values in object destructuring?
Yes, e.g., const { a = 10 } = obj;
How do you ignore values when destructuring an array?
Use commas to skip values, e.g., const [, , b] = [1, 2, 3];
Can you destructure values returned from a function?
Yes, e.g., const [a, b] = f();
Can you destructure iterables other than arrays?
Yes, e.g., const [a, b] = new Map([[1, 2], [3, 4]]);
How does the && operator work in JSX conditional rendering?
If the condition on the left of && is true, the JSX on the right will be rendered. If false, it will be ignored.
How are event listeners specified in JSX?
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.
When should you use React Fragments in JSX?
Use React Fragments (<></>) to group multiple elements without adding extra nodes to the DOM.
What is an example of exporting a React component?
export default MyComponent;
What is an example of importing a React component?
import MyComponent from './MyComponent';
How can React components be shared between different files?
```// Exporting a component
export default MyComponent;
// Importing a component
import MyComponent from ‘./MyComponent’;
~~~
What two methods are required to render a React component to the DOM?
.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>)
~~~
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>
<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’.
What is the syntax for initialzing a useState()?
const [isSomething, setSomething] = useState(optionalDefaultValue);
How can you simplify this React event handler using object destructuring?
```const handleChange = (event) => {
const newEmail = event.target.value;
setEmail(newEmail);
}
~~~
```const handleChange = ({ target }) => setEmail(target.value);
~~~
How can you add a new item?
```const [cart, setCart] = useState([]);
const addItem = (item) => {
???
};```
setCart(prevCart => { return [item, ...prevCart]; })
prevCart is basically the isState of the cart. …prevCart adds it to the item.
What is the basic syntax of useState?
const [state, setState] = useState(initialState);
- state: current state value - setState: function to update the state - initialState: initial value of the state
How to copy over a previous state in React. So keep Data when user enters new data?
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 do you add an event listener in a useEffect hook?
Use
document.addEventListener('event', handler)inside the useEffect hook.
How do you clean up an event listener in a useEffect hook?
Return a cleanup function from the useEffect hook that calls
return () => { document.removeEventListener('event', handler); } }, []);.
What does the empty dependency array [] in useEffect do?
It ensures the effect runs only once when the component mounts.
How do you define an event handler function in a React component?
Define the function as a constant, e.g.,
const increment = () => { /* logic */ };
How do you pass a reference to an event handler in addEventListener?
Pass the function name without parentheses, e.g.,
document.addEventListener('mousedown', increment).
Why is it important to use the same function reference in addEventListener and removeEventListener?
To ensure the event listener is correctly added and removed, preventing memory leaks and unexpected behavior.
How do you run an effect only when a component mounts?
Pass an empty array [] as the second argument to useEffect().
What does JSON.stringify(response, ‘’, 2) do?
Converts the response object to a readable string with indentation for easy viewing.
How do you fetch data in a useEffect hook?
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]);
~~~
Where should you call unsubscribe() in a function component to ensure it is executed before the component is removed from the DOM?
In a cleanup function, returned by the first argument of the Effect Hook.
How do you correctly set up and clean up an event listener for ‘mousedown’ events in a function component?
```useEffect(() => {
document.addEventListener(‘mousedown’, increment);
return () => {
document.removeEventListener(‘mousedown’, increment);
};
}, []);
~~~
Why should we use Hooks with function components?
Hooks add state to function components.
How do you fetch and render data from a server in a function component?
```function FetchAndViewData({ endpoint }) {
const [data, setData] = useState(null);
useEffect(() => {
get(endpoint).then((response) => setData(response.data));
}, [endpoint]);
return <div>{JSON.stringify(data, ‘’, 2)}</div>;
}
~~~