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 where state manages the input values:
const [formData, setFormData] = useState({ name: "", email: "" }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; return ( <form> <input name="name" value={formData.name} onChange={handleChange} /> <input name="email" value={formData.email} onChange={handleChange} /> </form> );
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 />)
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 for arrays and objects?
Use the spread syntax on collections of dynamic data to copy the previous state into the next state like so:
setArrayState((prev) => [...prev, newItem]);
and
setObjectState((prev) => ({ ...prev, key: newValue }));
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 is props in React?
props is an object that holds values passed from a parent component to 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?
Use .filter() to create a new array without the item:
const [items, setItems] = useState(["Apple", "Banana", "Cherry"]); const removeItem = (itemToRemove) => { setItems(prevItems => prevItems.filter(item => item !== itemToRemove)); };
✅ prevItems is the current array state before updating.
✅ .filter() returns a new array, ensuring state updates correctly in 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.
What is the
<Outlet />component in React Router?
<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.
What does useParams return if you visit /users/123 in a route defined as /users/:id?
It returns { id: “123” }, where the key id matches the dynamic part of the URL.
What is the purpose of the
<Link>component in react-router-dom?
The
<Link>component creates navigational links that change routes without causing a full page reload, using client-side navigation for faster performance.
What is the difference between
<Link>and
<NavLink>?
<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.
How do you define a loader for a route in React Router?
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().
What is useLoaderData() used for?
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.
What is <Form> in react-router-dom used for?
<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>
What does the action function do in React Router?
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.
How do you access form data inside an action function?
You can access form data in an action by using request.formData() to retrieve the form values from the submitted data.
What is redirect() in React Router’s action?
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”)
What happens when a form is submitted using
<Form method="post">in React Router?
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.
What are the possible values of navigation.state from useNavigation?
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).
How can you detect if a form is currently being submitted using useNavigation?
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.
How do you use useNavigation to display a loading spinner when navigating between routes?
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.
What is the formData property of the navigation object in useNavigation?
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.
What does navigation.formMethod indicate when using useNavigation?
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.
How do you disable a submit button while a form is being submitted with useNavigation?
You can conditionally disable the button using:
<button type="submit" disabled={navigation.state === "submitting"}> Submit </button>
How can you display different messages based on whether the app is submitting a form or loading a new route using useNavigation?
You can use:
if (navigation.state === "submitting") { return <p>Submitting form...</p>; } else if (navigation.state === "loading") { return <p>Loading new route...</p>; }
What is the default state of navigation.state when there is no active navigation or form submission?
The default state is “idle”, meaning no navigation or form submission is currently happening.
What is the purpose of redirect() in React Router?
- 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.
What does params represent in an action function in React Router?
- 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.
Explain the code for programmatically submitting a form using useSubmit.
const submit = useSubmit(); submit(formData, { method: "post", action: "/contacts/new" });
- 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.
What are the different states in useFetcher?
- “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.
What does this code do?
onChange={(event) => { const isFirstSearch = q == null; submit(event.currentTarget.form, { replace: !isFirstSearch, }); }}
- 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.
What is useLoaderData used for?
- 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.
What is the difference between useSubmit and useFetcher?
- 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.
What does useNavigate do?
- 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();.
What is the purpose of localforage.getItem(“contacts”) in this function?
let contacts = await localforage.getItem("contacts");
- 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.
Q: What does useFetcher.load() do?
- 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.
How do you trigger a form submission with useFetcher without reloading the page?
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).
How do you define a root route with a pathless route for error handling in object-based route configuration?
createBrowserRouter([ { path: "/", element: <Root />, errorElement: <ErrorPage />, children: [ { errorElement: <ErrorPage />, children: [ { path: "contacts/:contactId", element: <Contact /> }, ], }, ], }, ]);
How do you define a root route with a pathless route for error handling in JSX route configuration?
<Route path="/" element={<Root />} errorElement={<ErrorPage />}> <Route errorElement={<ErrorPage />}> <Route path="contacts/:contactId" element={<Contact />} /> </Route> </Route>
How do you create a QueryClient instance?
You create a QueryClient using:
import { QueryClient } from 'react-query'; const queryClient = new QueryClient();
How do you set up QueryClientProvider in your app?
You wrap your app with QueryClientProvider, passing the QueryClient instance like so:
<QueryClientProvider client={queryClient}> <App /> </QueryClientProvider>
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.
useQuery
What are the key arguments of useQuery?
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);
What values does useQuery return?
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.
How does React Query handle caching?
React Query caches query results and automatically serves them until they become stale. Cached data is reused across components, reducing unnecessary network requests.
What does useMutation do in React Query?
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.
How do you use useMutation in React Query?
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), }); });
What states does useMutation return?
useMutation returns:
- mutate: Function to trigger the mutation.
- isLoading: Mutation is in progress.
- isError: Mutation failed.
- isSuccess: Mutation succeeded.
How does React Query handle background refetching?
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.
How do you handle errors in React Query?
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>;
What are the two arguments passed to createPortal?
- The JSX you want to render (e.g., <div>Modal content</div>).
- The DOM element where you want to render it (e.g., document.getElementById(‘modal-root’)).
Where should you create the DOM node for a modal in your HTML?
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).
In the Modal component, why do we use the useRef hook?
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.
When should you call setShowModal(true) in your component?
Call setShowModal(true) when you want to open the modal (e.g., on a button click).
What is the purpose of conditional rendering (showModal && <Modal></Modal>)?
Conditional rendering ensures that the Modal component is only rendered when showModal is true, keeping the modal hidden when it’s not needed.
How does createPortal help in avoiding CSS layout issues when using modals?
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.
What is the purpose of using useEffect in the Modal component?
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).
Where should the modal content be rendered in the DOM?
The modal content should be rendered inside a dedicated DOM element like #modal-root, which is outside the main React DOM tree.
Why is useState needed in the parent component that uses the Modal?
useState is needed to control whether the modal is shown or hidden. This state (e.g., showModal) is toggled to conditionally render the modal.
How can you pass content to a modal using children?
```<Modal></Modal>
<div>Modal content goes here</div>
</Modal>
~~~
How can you ensure the modal is closed when the user clicks a “Close” button?
You can ensure the modal closes by calling setShowModal(false) in the button’s onClick handler to hide the modal.
How do you structure a useEffect hook in the modal component to append and remove the modal from the DOM?
```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.
How would you describe a function component?
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.
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>; }
In the return statement, wrap fave in curly braces.
return <h1>{fave}</h1>;
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> ); }
<img src={fuzzyFox.src} alt={fuzzyFox.alt} />
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>; }
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>; }
In React, what happens if there are no props passed to a component?
The component will use default values for any missing props.
Which import statement allows a function component to use the State and Effect Hooks to generate dynamic JSX?
´´´
import React, { useEffect, useState } from ‘react’
´´´
Why should we use Hooks with function components?
Hooks add state to function components.
How to install react router?
npm install react-router-dom
How to import react router?
import { createBrowserRouter } from 'react-router-dom';
at top of the file.
How to make RouterProvider available to our entire application?
import { RouterProvider, createBrowserRouter } from 'react-router-dom'; const router = createBrowserRouter( /* application routes are defined here */ ); export default function App () { return ( <RouterProvider router={ router } /> ); }
What is the purpose of the createRoutesFromElements utility in React Router?
It converts JSX route elements into route objects, which can then be used by createBrowserRouter.
What two main props does a route element take in React Router?
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/> } />
How do you pass a non-empty array of routes to the router?
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> ) ));
What alternatives to anchor tags does React Router offer and what do they do?
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.
How can you navigate conditionally to a certain link?
First
~~~
import { Navigate } from ‘react-router-dom’;
~~~
Than in the function:
~~~
const UserProfile = ({ loggedIn }) => {
if (!loggedIn) {
return (
<Navigate></Navigate>
)
}
return (
// … user profile content here
)
}
~~~
How to navigate imperatively with React Router?
First
~~~
import { useNavigate } from ‘react-router-dom’;
~~~
Than initialize:
~~~
const navigate = useNavigate()
~~~
Than e.g.:
~~~
return (
<button onClick={() => navigate(-1)}>
Go Back
</button>
)
~~~
How do you retrieve the search Parameters with react route?
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”
What if we want to navigate to a path and include query parameters? e.g. /list?order=ASC
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}
})
~~~
How to show the active link in NavLink?
Using destructuring syntax and a template string which checks if isactive is true:
<NavLink to="/" className={ ({ isActive }) => `nav-link ${isActive ? 'nav-link-active' : ''}`} </NavLink>
How to import css modules and use the styles in react?
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>; }
How to bootstrap a default Next.js app?
npx create next app my-app
What is the purpose of the App Router in Next.js?
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.
How are folders and reserved files used in the Next.js App Router?
Folders define path segments, and reserved files like page.tsx define the UI for those segments.
How do you create nested routes in Next.js?
Nested routes are created by nesting folders within the app directory.
What Next.js tools provide SPA-like navigation?
The useRouter() hook and <link></link> component provide SPA-like navigation in Next.js.
What does the useRouter() hook return, and what can you do with it?
It returns a router object with methods like push(path), back(), and forward() for navigation.
What is the role of the page.tsx file in Next.js?
It defines a unique UI for its containing path segment and must default export a React component.
What are layout.tsx and template.tsx files used for in Next.js?
Both are used to create shared UIs, but layout.tsx persists across navigations while template.tsx re-instantiates.
What is a dynamic segment in Next.js, and how is it created?
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.
How do you create a catch-all dynamic segment in Next.js?
A catch-all dynamic segment is created by prefixing the dynamic segment with ellipses, e.g., /app/articles/[…articleIds].
What are some of the special reserved files in Next.js and their purposes?
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.
How do layout.tsx and page.tsx work together in next.js?
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 </> ) }
How do you create a new route in next.js?
By adding a new folder nad inside this new folder creating a page.tsx with all the content of the new route.
How can you prevent page reloads in next.js when clicking links?
By using Link instead of a tags and importing Link beforehand.
import Link from 'next/link' <Link href={`/users/${userId}`} > User: {userId} </Link>
How can you indicate which Nav Links are active in next.js?
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> )
What is the useRouter hook in Next.js?
The useRouter hook gives access to the Next.js router object, allowing you to inspect the current route or programmatically control navigation between pages.
How do you import and use the useRouter hook in a Next.js component?
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> ); };
What does the router.push method do in Next.js?
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.
What is the syntax for router.push in Next.js?
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.
How do you use router.push to navigate to /about on button click?
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> ); };
How can you use router.push to navigate to a dynamic route in Next.js?
router.push({ pathname: '/product/[id]', // Dynamic path query: { id: '123' } // Passing query params (id = 123) });
This would navigate to /product/123.
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?
useEffect(() => { setIsDuplicate(contacts.some(contact => contact.userName === userName)); }, [userName, contacts]);
-
contacts.some()
checks if any contact’suserName
matches the givenuserName
. -
setIsDuplicate
updates the state withtrue
if a match is found, otherwisefalse
. - This hook runs whenever
userName
orcontacts
changes.
In React, how do you update the name
state with each input change for a text input field?
<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.
How can you capture the input value from a form in React?
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)} />
How do you create a new item object when the form is submitted?
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(), };
What is the purpose of mapping over the items array to render a list?
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>
How can you validate the input before adding a new item in React?
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; }
What is the difference between controlled and uncontrolled components in React?
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} />
How do you style a React component using global CSS?
Import the CSS file directly into the component:
import './styles.css';
Apply classes using the className attribute in JSX:
<div className="container"></div>
How do you scoped style a React component using CSS?
Import the CSS file as a module:
import styles from './styles.module.css';
Apply classes using styles.className:
<div className={styles.container}></div>
How do you toggle a class based on a condition in a JSX element?
Use a conditional expression:
className={condition ? 'className' : ''}
What is the purpose of the handleChecked function in a checkbox component?
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 ) ); };
How do you update the state of an array in React without mutating the original array?
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 ) );
What is the difference between the checked attribute and the onChange event in a checkbox?
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)} />
What should the initial state of an item include when adding it to a list?
Each item should have properties like name, id, and checked (initialized to false).
const newItem = { name: item.value, id: Date.now(), checked: false };
How can you implement a delete button for a todo list e.g.?
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>
How can you update state in React when the user types into an input field?
Use the onChange event handler to update the corresponding state for each input.
<input type="text" value={stateValue} onChange={(e) => setStateValue(e.target.value)} />
How do you clear form fields after a successful submission in React?
Reset the state values to empty strings in the handleSubmit function after successfully adding the data.
setUserName(""); setPhoneNumber(""); setEmail("");
How can you reset or update error messages dynamically when a user types in a field?
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"); } }}
How do you handle duplicate name checks in a contact form using useEffect?
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]);
How would you render an object’s values in a list of <p> tags using React?
{Object.values(obj).map((value, index) => ( <p key={index}>{value}</p> ))}
What is .map() commonly used for in React?
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> );
How can you remove immutable an item at a given index?
With the spreadoperator and two slice methods:
export const removeItemAtIndex = (list, index) => { return [...list.slice(0,index), ...list.slice(index+1)] };
What is the purpose of the “main” field in package.json?
It specifies the entry point of your application, usually a file like index.js.
What command is used to install a development dependency?
npm install [package-name] –save-dev
What does the caret (^) symbol mean in dependency versions?
The caret (^) allows updates for the latest minor or patch version while maintaining the major version.
What does the tilde () symbol mean in dependency versions?
The tilde () only allows updates for the latest patch version while maintaining the major and minor versions.
What is the best way to update state based on its current value in React?
Use the functional updater form of setState. It ensures you’re working with the latest state value, avoiding race conditions when multiple updates occur in quick succession.
setCoins(prevCoins => prevCoins + collectedCoins);
React state updates are asynchronous, and directly using the state variable (coins) might not reflect its latest value.
How can you perform a logic imediateley in React without waiting for the rerendering?
Use the value inside the setState callback:
setValue(prevValue => { const newValue = prevValue - 1; return newValue; });
What are Controlled Components in React?
Controlled components are form elements whose values are managed by React state. The component’s state determines the input value, making React the single source of truth.
Example:
const [text, setText] = useState(""); const handleChange = (e) => { setText(e.target.value); }; return <input type="text" value={text} onChange={handleChange} />;
This ensures that the input value is always in sync with the component’s state.
How do you pass props from a parent to a child component?
You pass them as attributes inside the child component tag.
<Child username="Marco" age={25} />
If a parent passes { username: “Marco”, age: 25 }, what does props contain?
props = { username: "Marco", age: 25 }
How do you use props inside a child component?
function Child(props) { return <p>Username: {props.username}</p>; }
How can you avoid writing props. every time?
Use destructuring!
function Child({ username, age }) { return <p>Username: {username}, Age: {age}</p>; }