Title: React Framework — LearnCoachAssist

Q: What is React?
A: React is a JavaScript library developed by Facebook for building user interfaces. It uses a component-based architecture and a virtual DOM for efficient rendering of dynamic, interactive web applications.

Q: What is JSX?
A: JSX stands for JavaScript XML. It is a syntax extension that lets you write HTML-like code inside JavaScript. JSX is transpiled to React.createElement() calls by tools like Babel before running in the browser.

Q: What is the Virtual DOM?
A: The Virtual DOM is a lightweight in-memory representation of the real DOM. When state changes, React creates a new virtual DOM tree, diffs it against the previous one, and applies only the minimal set of changes to the real DOM — a process called reconciliation.

Q: What is a functional component in React?
A: A functional component is a plain JavaScript function that accepts props as an argument and returns JSX. Example:
function Greeting({ name }) { return <h1>Hello, {name}</h1>; }

Q: What is a class component in React?
A: A class component is an ES6 class that extends React.Component and must implement a render() method. It can hold local state and use lifecycle methods:
class App extends React.Component { render() { return <h1>Hello</h1>; } }

Q: What are props in React?
A: Props (short for properties) are read-only inputs passed from a parent component to a child component. They allow data to flow top-down (unidirectional) through the component tree and cannot be modified by the receiving component.

Q: What is state in React?
A: State is a mutable data object managed within a component that determines how the component renders and behaves. When state changes, React re-renders the component. In functional components, state is managed with the useState hook.

Q: How does the useState hook work?
A: useState returns an array with two elements: the current state value and a setter function.
const [count, setCount] = useState(0);
Calling setCount(count + 1) schedules a re-render with the updated value.

Q: What is the useEffect hook?
A: useEffect lets you perform side effects in functional components (data fetching, subscriptions, DOM manipulation). It runs after render.
useEffect(() => { /* effect */ return () => { /* cleanup */ }; }, [dependencies]);

Q: What does the dependency array in useEffect do?
A: The dependency array controls when the effect runs:
- [] — runs only on mount
- [a, b] — runs when a or b change
- No array — runs after every render

Q: What is the useContext hook?
A: useContext lets a component consume a value from a React context without wrapping it in a Context.Consumer.
const value = useContext(MyContext);
The component re-renders whenever the context value changes.

Q: What is the useReducer hook?
A: useReducer is an alternative to useState for complex state logic. It accepts a reducer function and initial state:
const [state, dispatch] = useReducer(reducer, initialState);
You update state by dispatching actions to the reducer.

Q: What is the useMemo hook?
A: useMemo memoizes a computed value so it is only recalculated when its dependencies change:
const result = useMemo(() => expensiveCalc(a, b), [a, b]);
It helps avoid expensive recalculations on every render.

Q: What is the useCallback hook?
A: useCallback returns a memoized version of a callback function that only changes when its dependencies change:
const handler = useCallback(() => doSomething(id), [id]);
Useful when passing callbacks to optimized child components.

Q: What is the useRef hook?
A: useRef returns a mutable ref object whose .current property persists across renders without causing re-renders.
Common uses:
- Accessing DOM elements directly
- Storing mutable values (e.g., timers, previous state)

Q: How do you access a DOM element with useRef?
A: Create a ref and attach it to a JSX element via the ref attribute:
const inputRef = useRef(null);
<input ref={inputRef} />
Then access it: inputRef.current.focus();

Q: What is the Context API in React?
A: The Context API provides a way to share values between components without passing props at every level. It consists of:
- React.createContext() — creates a context
- Provider — supplies the value
- useContext() — consumes the value

Q: How do you create and use a React Context?
A: const ThemeCtx = React.createContext('light');
Provide it: <ThemeCtx.Provider value="dark">...</ThemeCtx.Provider>
Consume it: const theme = useContext(ThemeCtx);

Q: What are React lifecycle methods?
A: Lifecycle methods are special methods on class components invoked at specific phases:
- Mounting: componentDidMount
- Updating: componentDidUpdate
- Unmounting: componentWillUnmount
Functional components use useEffect instead.

Q: How does useEffect replicate componentDidMount?
A: Pass an empty dependency array to useEffect:
useEffect(() => { // runs once on mount }, []);
The effect fires after the first render only, mimicking componentDidMount.

Q: How does useEffect replicate componentWillUnmount?
A: Return a cleanup function from useEffect with an empty dependency array:
useEffect(() => { return () => { // runs on unmount }; }, []);

Q: Why are keys important in React lists?
A: Keys give each element a stable identity so React can efficiently track, reorder, add, or remove items during reconciliation. Without proper keys, React may re-render entire lists unnecessarily or produce bugs with component state.

Q: What value should you use for keys in a list?
A: Use a unique, stable identifier such as a database ID. Avoid using the array index as a key when the list can be reordered, filtered, or modified, because it causes incorrect state mapping and rendering bugs.

Q: What are React Fragments?
A: Fragments let you group multiple elements without adding an extra DOM node.
Syntax: <React.Fragment>...</React.Fragment> or the shorthand <>...</>. The shorthand does not support the key prop.

Q: What are React Portals?
A: Portals let you render a child into a different DOM node outside the parent component's DOM hierarchy:
ReactDOM.createPortal(child, domNode)
Common use cases include modals, tooltips, and popups that need to break out of overflow or z-index constraints.

Q: What is an Error Boundary?
A: An Error Boundary is a class component that catches JavaScript errors in its child component tree during rendering, lifecycle methods, and constructors. It implements static getDerivedStateFromError() and/or componentDidCatch() to display a fallback UI.

Q: Can functional components be Error Boundaries?
A: No. Error Boundaries can only be implemented as class components because they rely on static getDerivedStateFromError() and componentDidCatch(), which have no hook equivalents. However, libraries like react-error-boundary provide a wrapper.

Q: What is lifting state up in React?
A: Lifting state up means moving shared state to the closest common ancestor of the components that need it. The ancestor holds the state and passes it down as props, enabling sibling components to share and synchronize data.

Q: What is prop drilling and how do you avoid it?
A: Prop drilling is passing props through many intermediate components that don't use them, just to reach a deeply nested child. Solutions:
- Context API
- State management libraries (Redux, Zustand)
- Component composition

Q: What is conditional rendering in React?
A: Conditional rendering means showing different UI based on conditions. Techniques:
- Ternary: {isLoggedIn ? <Dashboard /> : <Login />}
- Logical AND: {hasError && <Error />}
- Early return inside the component

Q: What is the difference between controlled and uncontrolled components?
A: Controlled: Form data is handled by React state; the input value is set via value and updated via onChange.
Uncontrolled: Form data is managed by the DOM itself; you read values with a ref. Controlled components are generally preferred.

Q: What is React.memo?
A: React.memo is a higher-order component that memoizes a functional component. It skips re-rendering if the props have not changed (shallow comparison):
const MemoComp = React.memo(MyComponent);

Q: What is the difference between useMemo and useCallback?
A: useMemo memoizes a computed value: useMemo(() => val, [deps]).
useCallback memoizes a function reference: useCallback(fn, [deps]).
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

Q: How do you handle events in React?
A: Events use camelCase naming and accept a function reference:
<button onClick={handleClick}>Click</button>
React wraps native events in a SyntheticEvent for cross-browser compatibility. Do not call the function: onClick={handleClick()} is wrong.

Q: What is a SyntheticEvent in React?
A: A SyntheticEvent is React's cross-browser wrapper around the native browser event. It has the same interface as native events (stopPropagation, preventDefault) but works consistently across all browsers.

Q: What is the children prop in React?
A: props.children contains the content between the opening and closing tags of a component:
<Card><p>Hello</p></Card>
Inside Card, props.children is the <p> element. It enables component composition.

Q: What are Higher-Order Components (HOCs)?
A: A HOC is a function that takes a component and returns a new enhanced component:
const Enhanced = withAuth(MyComponent);
HOCs enable cross-cutting concerns like authentication, logging, and theming without modifying the original component.

Q: What are custom hooks in React?
A: Custom hooks are JavaScript functions whose names start with use that can call other hooks. They let you extract and reuse stateful logic across components without changing the component hierarchy. Example: function useWindowSize() { ... }

Q: What are the rules of hooks?
A: - Only call hooks at the top level — not inside loops, conditions, or nested functions
- Only call hooks from React function components or custom hooks
These rules ensure hooks are called in the same order on every render.

Q: What is React.StrictMode?
A: <React.StrictMode> is a development-only wrapper that activates additional checks and warnings:
- Detects unsafe lifecycle methods
- Warns about deprecated APIs
- Double-invokes certain functions to detect side effects
It has no effect in production.

Q: What is reconciliation in React?
A: Reconciliation is the diffing algorithm React uses to compare the previous and new virtual DOM trees. It determines the minimum number of operations needed to update the real DOM, using heuristics like element type comparison and keys.

Q: What is the difference between state and props?
A: Props are passed in from a parent and are read-only. State is managed internally by the component and is mutable via setter functions. Both trigger a re-render when they change.

Q: What does useState return and how do you update state?
A: useState returns [value, setValue]. Update with a new value: setValue(5), or with a functional updater when the new state depends on the old: setValue(prev => prev + 1). The functional form avoids stale state bugs.

Q: Why is setState asynchronous in React?
A: State updates are batched for performance. React groups multiple setState calls into a single re-render to avoid unnecessary DOM updates. This means you cannot rely on reading the new state value immediately after calling the setter.

Q: What is the purpose of the key prop in React?
A: The key prop helps React identify which items have changed, been added, or removed in a list. It must be unique among siblings. Proper keys enable efficient reconciliation and preserve component state correctly.

Q: How do you pass data from child to parent in React?
A: Pass a callback function as a prop from the parent to the child. The child calls the function with data as an argument:
<Child onSubmit={handleData} />
Inside Child: props.onSubmit(value);

Q: What is lazy loading in React?
A: Lazy loading defers loading a component until it is needed, reducing the initial bundle size:
const LazyComp = React.lazy(() => import('./MyComp'));
Wrap it in <Suspense fallback={<Spinner />}> to show a fallback while loading.

Q: What is React.Suspense?
A: <Suspense> lets you display a fallback UI (e.g., a spinner) while waiting for lazy-loaded components or asynchronous data to resolve:
<Suspense fallback={<Loading />}><LazyComponent /></Suspense>

Q: What is the useLayoutEffect hook?
A: useLayoutEffect fires synchronously after DOM mutations but before the browser paints. Use it when you need to read layout from the DOM and re-render synchronously (e.g., measuring element size). Prefer useEffect for most side effects.

Q: How do you optimize a React application's performance?
A: Key techniques:
- React.memo to avoid unnecessary re-renders
- useMemo / useCallback to memoize values and functions
- Code splitting with React.lazy and Suspense
- Proper key usage in lists
- Virtualizing long lists with libraries like react-window