← Back to Week 8

Quiz 4 Study Guide

This study guide covers possible questions for Quiz 4. I answered each question based on my understanding to help me prepare.

Sources:

Take Practice Quiz

Q1. How can a child component update its parent's state?

The parent passes a callback function as a prop to the child. The child calls this callback (e.g., props.onUpdate(newValue)) when it needs to update the parent's state. The child never directly accesses or modifies the parent's state variable or setter function.

Q2. How does one define props that should be passed into a React component?

Props are passed as XML-style attributes when rendering the component: <MyComponent name="Ada" age={36} />. Inside the component, they are accessed through the props parameter object: props.name, props.age. You can also use destructuring: function MyComponent({ name, age }).

Q3. How is the map() function commonly used in React components?

The map() function transforms an array of data into an array of React components for rendering. For example: props.items.map((item) => <ListItem key={item.id} data={item} />). Each mapped element needs a unique key prop so React can efficiently track changes.

Q4. How should a child component update its parent's state?

By calling a callback function that was passed down as a prop from the parent. The parent defines a handler function that calls its own state setter, then passes that handler to the child. The child invokes props.onAction(data) when needed. This maintains unidirectional data flow.

Q5. What content is usually found in a React application's index.html file?

A minimal HTML file containing a single <div id="root"></div> element where all React components are injected. It also loads the entry point script (src/main.jsx) which bootstraps the React application using ReactDOM.createRoot().

Q6. What does a React component's state represent?

State represents internal, changeable data within a component that changes over time, usually due to user interaction. When state changes, React automatically re-renders the component to reflect the updated data. State is private to the component that owns it.

Q7. What does ReactDOM.createRoot() do?

It creates a React rendering context (root) for a specified DOM element, enabling React to manage that element's content. It takes a DOM element as an argument (e.g., document.getElementById('root')) and returns a root object with a .render() method to render React components into the DOM.

Q8. What does the command npm run dev do in a Vite React project?

It starts the Vite development server (typically at localhost:5173) which transpiles JSX into regular JavaScript, manages module dependencies, automatically reloads the browser when files change (hot module replacement), and displays syntax errors in the browser.

Q9. What does the second argument in useEffect(callback, []) signify?

The second argument is the dependency array. An empty array [] means the effect runs only once when the component first mounts (similar to "on component load"). If variables are listed in the array, the effect re-runs whenever those values change. Omitting the array entirely causes the effect to run after every render.

Q10. What does the useState() function return?

It returns an array with exactly two elements: the current state value and a setter function to update it. Use array destructuring to assign them: const [count, setCount] = useState(0). The setter function name conventionally follows the pattern setVariableName.

Q11. What does "lifting state up" mean in React?

It means moving shared state to the closest common ancestor (parent) of the components that need it. The parent owns the state and passes it down as props. Children that need to modify the state receive callback functions as props. This ensures a single source of truth for the data.

Q12. What happens when you call a state setter function?

React schedules a re-render of the component with the new state value. The component function is called again, and the JSX is regenerated with the updated data. The state update is asynchronous, so the new value is not immediately available in the same event handler where the setter was called.

Q13. What is a controlled input in React forms?

A controlled input is a form element whose value is controlled by React state. It requires both a value attribute tied to state and an onChange handler that updates state on every change: <input value={text} onChange={(e) => setText(e.target.value)} />. React becomes the single source of truth for the input's value.

Q14. What is JSX?

JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code directly in JavaScript. It gets transpiled (converted) into React.createElement() calls by tools like Babel/Vite. JSX uses className instead of class, requires self-closing tags for void elements, and uses curly braces {} for JavaScript expressions.

Q15. What is React primarily used for?

React is a JavaScript library primarily used for building user interfaces through reusable components. It efficiently updates the DOM using a virtual DOM, enabling developers to create interactive, data-driven web applications. React takes a declarative approach: you describe what the UI should look like, and React handles the updates.

Q16. What is the correct way to define a React function component?

A function component is a JavaScript function that starts with a capital letter, accepts a props parameter, and returns JSX (a single root element). Example: function MyComponent(props) { return <div>{props.text}</div>; }. It is rendered as <MyComponent />, never called directly as MyComponent().

Q17. What is the main advantage of using React compared to DOM functions?

React automatically tracks data changes and efficiently re-renders only the parts of the UI that need updating through its virtual DOM. With vanilla DOM functions, you must manually create, update, and remove elements. React's declarative approach lets you describe the desired UI state, and it handles the DOM manipulation.

Q18. What is the main difference between props and state?

Props are passed from a parent component and are read-only (immutable) from the receiving component's perspective. State is internal data managed within the component that changes over time, usually through user interaction. Props flow down, state is local. If data doesn't change, use props; if it changes over time, use state.

Q19. What is the primary purpose of the useEffect() hook in React?

The useEffect() hook handles side effects in function components, such as fetching data from APIs, setting up subscriptions, or directly manipulating the DOM. It runs after the component renders and can be controlled with a dependency array to determine when it re-runs.

Q20. What is the purpose of React.StrictMode?

React.StrictMode is an optional wrapper component that enables additional error checking and warnings during development. It helps identify deprecated practices, unsafe lifecycles, and potential bugs by intentionally double-rendering components. It only runs in development mode and has no effect in production.

Q21. What is the recommended way to organize React components in large projects?

Place each component in its own file inside a src/components/ directory. Use named exports (export function MyComponent) and import them where needed. Group related components together. The main App.js serves as the top-level component that composes the others.

Q22. What type of data can props hold?

Props can hold any JavaScript value: strings, numbers, booleans, arrays, objects, functions (callbacks), and even other React components. String values can be passed directly in quotes, while all other types use curly braces: <Component name="Ada" age={36} items={array} onClick={handler} />.

Q23. Which attribute is used to register a click event in React?

The onClick attribute (camelCase) is used on HTML elements: <button onClick={handleClick}>Click</button>. Pass a function reference, not a function call. Event listeners only attach to HTML elements (lowercase tags), not custom React components.

Q24. Which attribute name is used in JSX instead of class?

className is used instead of class because class is a reserved keyword in JavaScript. Example: <div className="container">. Similarly, htmlFor is used instead of for on label elements.

Q25. Which hook is used for side effects like data fetching?

useEffect() is used for side effects including data fetching, subscriptions, and DOM manipulation. It takes a callback function and an optional dependency array: useEffect(() => { fetch(url).then(...) }, []). The empty array ensures the fetch runs only once on mount.

Q26. Which is the recommended way to define an event handler for a React component?

Define the handler as a function inside the component, then pass it by reference (without parentheses) to the event prop: const handleClick = () => { ... }; return <button onClick={handleClick}>. Don't use onClick={handleClick()} as that calls the function immediately during render.

Q27. Which of the following best describes what values can be included inside a JSX inline expression?

Any JavaScript expression that produces a value can go inside curly braces {}: variables, function calls, ternary operators, arithmetic, array methods like .map(). Statements like if/else, for loops, or variable declarations cannot be used directly inside JSX expressions.

Q28. Which of the following is NOT true about React components?

It is NOT true that components can be called as regular functions (e.g., MyComponent()). Components must be rendered as JSX elements: <MyComponent />. Components ARE: functions that return JSX, reusable, composable, and must start with a capital letter.

Q29. Which of the following should NOT be stored in a component's state?

Values that can be derived (computed) from existing state or props should NOT be stored in state. For example, if you have a list in state, don't also store the list length in state since you can compute it with list.length. Also avoid storing props in state, and don't use state for values that never change.

Q30. Which React hook is used to manage state in function components?

useState() is used to manage state. It accepts an initial value and returns an array with the current state and a setter function: const [value, setValue] = useState(initialValue). Import it from React: import { useState } from 'react'.

Q31. Which tool transpiles JSX into regular JavaScript?

Vite (using Babel under the hood) transpiles JSX into regular JavaScript (React.createElement() calls) that browsers can understand. Vite also bundles modules, handles dependencies, and provides a development server with hot module replacement.

Q32. Why is the key prop important when rendering lists?

The key prop gives each list item a stable, unique identity so React can efficiently track which items have changed, been added, or removed during re-renders. Without keys, React must re-render the entire list. Keys should be unique identifiers from the data (like IDs), not array indices.

Q33. Why might logging out a state variable immediately after calling a state setter function print the old value?

Because state updates in React are asynchronous. When you call a setter like setCount(5), React schedules the update but doesn't apply it immediately. The component hasn't re-rendered yet, so count still holds the old value. To see the new value, log at the top of the component function (render level), where it reflects the latest state after re-render.

Q34. Why should you never update state directly using an assignment operator?

Directly mutating state (e.g., stateVar = newValue or stateArray.push(item)) does NOT trigger a re-render. React only knows to update the UI when the setter function is called. You must always create new copies of objects/arrays using spread operator and pass them to the setter: setItems([...items, newItem]).

Q35. Why should you use controlled inputs in a React form?

Controlled inputs keep React state as the single source of truth for form data, preventing React and the DOM from getting out of sync. This makes it easy to validate, transform, or submit form data since it's always available in state. It also enables features like disabling a submit button until the form is valid.