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 React with Vite?
npm create vite@latest my-react-app --template react
Than cd into the folder
npm install
To start the development server:
npm run dev
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>;
}
~~~
Which event handler best adds a clicked item to an array state variable?
const addItem = ({ target }) => { setItems((prev) => [target.value, ...prev]); };
How do you pass a function as a prop in React?
<ComponentName propName={functionName} />
How do you calculate the remaining time until an event in JavaScript?
Subtract the current time from the event time: eventTime - Date.now()
What does props.addThought(thought) do in a child component?
It calls the addThought function passed from the parent to add a new thought.
How do you filter out an item from an array in React?
```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.
Describe the typical hierarchy of components in a React application.
index.js -> App.js (root) -> Container Component -> Presentational Component.
How are props used in React components?
Props are passed as an object to components and can be destructured for easier access.
Where should the useState or useEffect hook be used?
The useState hook should be used in container components to manage state.
How does the rendering flow work in a React application?
The root component renders container components, which in turn render presentational components, forming a nested structure.
What is a necessary part of any “stateful” component?
An initialization of state using the useState hook because it establishes the initial state value and enables state management within the component efficiently.
How do you apply inline styles in React?
Use the style attribute with an object literal: <h1 style={{color: “red”}}>Hello, World!</h1>
How do you use an object variable for styles in React?
Define a style object and pass it to the style attribute:
~~~
const myStyle = { color: “red” };
<h1 style={myStyle}>Hello, World!</h1>
~~~
How should style names be written in React?
Style names must be in camelCase, e.g., background-color becomes backgroundColor.
How do you import a CSS module in a React component?
Import the module and use the styles object:
~~~
import styles from ‘./styles.module.css’;
<div className={styles.className}></div>
~~~
How do you define an object variable for styling in React?
Define it above the component:
~~~
const styleObj = { display: ‘flex’, marginBottom: ‘20px’ };
~~~
How do you apply an object variable for styling in React?
Use the style attribute with the object variable:
<div style={styleObj}>Content</div>
How do you apply a CSS module class in React?
Use the className attribute with the imported styles object:
~~~
<div className={styles.className}>Content</div>
~~~
What is the syntax to apply multiple styles in a React component?
Use a JavaScript object with multiple properties:
~~~
<div style={{ fontSize: 20, color: ‘red’ }}>Text</div>
~~~
What attribute is used to link a label to an input field in React?
htmlFor attribute
How do you handle radio button inputs in React?
By using the name attribute to group them and onChange to update the state.
How to bind the input field to the state value?
With the value attribute in form inputs
What is the shorthand for handling typing and deleting events in React inputs?
```<input onChange={(e) => setName(e.target.value)}
value={name} />
~~~
How to prevent adding Items to a list where item is already present in React?
With .some:
const handleAddToItemlist = (item) => { setItemlist(prevItems => { const isItemAlreadyAdded = prevItems.some ( (prevItem) => prevItem === item ); if (isItemAlreadyAdded) { return prevItems; } return [...prevItems, item]; }) }
What is useEffect used for in React?
useEffect is used to manage side effects in React functional components, such as data fetching, subscriptions, and manual DOM manipulation.
When does useEffect run in a React component?
useEffect runs after the component renders (i.e., after the JSX is returned and the DOM is updated).
How do you control when useEffect runs?
By passing a dependency array as the second argument to useEffect. The effect only runs when the dependencies in the array change.
What happens if you pass an empty array ([]) to useEffect?
The effect runs only once, after the initial render, and does not run on subsequent renders.