React Core and JSX

React Core & JSX

1) What is React?

Answer: React is a JavaScript library for building UI using components and a declarative approach. You describe what UI should look like for a state, React updates the DOM efficiently.

Example: return <h1>Hello</h1>

Trick: React = UI as a function of state.

2) What is JSX?

Answer: JSX is a syntax extension that lets you write HTML-like code inside JS. It compiles to React.createElement.

Example: <button onClick={handleClick}>Save</button>

Trap: JSX needs one parent wrapper (or fragment <>...</>).

3) Is JSX required in React?

Answer: No. You can use React.createElement, but JSX is cleaner and standard.

Example: React.createElement("div", null, "Hi")

4) What is a component?

Answer: A reusable UI unit. React has function components (modern standard) and class components (legacy).

Example: function Card(){ return <div/> }

Trick: Component = function returning UI.

5) Props vs State?

Answer: Props are inputs from parent (read-only). State is local data that changes over time.

Example: <User name="Al Amin" /> vs const [count,setCount]=useState(0)

Trick: Props flow down, state lives inside.

6) What does “declarative UI” mean?

Answer: You describe UI for each state; you don’t manually update DOM.

Example: isLoading ? <Spinner/> : <List/>

Trick: Declarative = what , not how .

7) What is Virtual DOM?

Answer: React builds a lightweight UI tree in memory and compares changes (diffing), then updates the real DOM efficiently.

Trap: It’s not always “faster,” but helps manage updates predictably.

8) What is reconciliation?

Answer: The process where React compares previous and new Virtual DOM and updates the real DOM.

Trick: Reconciliation = diff + apply changes.

9) What is the key prop and why needed?

Answer: Keys help React identify list items so it can update efficiently and avoid UI bugs.

Example: {items.map(i => <li key={i.id}>{i.name}</li>)}

Trap: Don’t use array index if list can reorder.

10) Why shouldn’t we use array index as key?

Answer: If items reorder/insert, index keys cause wrong component reuse → wrong state displayed.

Memory: Index key breaks when order changes.


Rendering & Conditional UI

11) How do you conditionally render in React?

Answer: Use ternary, &&, or early return.

Example: return isAdmin ? <Admin/> : <User/>

12) What is a fragment?

Answer: <>...</> groups children without adding extra DOM nodes.

Example: return <> <h1/> <p/> </>

13) What is “lifting state up”?

Answer: Moving state to the closest common parent so siblings can share it.

Example: Parent holds selectedId, passes props to two children.

Trick: Shared state lives in parent.

14) What are controlled components?

Answer: Form inputs whose value is controlled by React state.

Example:

Trap: Controlled = React is the source of truth.

15) Uncontrolled components?

Answer: Input manages its own state; React reads it using refs.

Example: const ref = useRef(); <input ref={ref} />

When: Simple forms, 3rd party libraries.

16) How to render a list?

Answer: Use .map() and a stable key.

Example: {users.map(u => <UserCard key={u.id} user={u} />)}

17) What is children prop?

Answer: It represents nested elements passed inside a component.

Example: <Modal><p>Hello</p></Modal>props.children

Trick: children = slot content.

18) What is prop drilling?

Answer: Passing props through many layers just to reach deep child.

Fix: Context, composition, or state management.

Trap: Don’t jump to Context too early.

19) What is React Context?

Answer: A way to share values (theme/auth) across tree without prop drilling.

Example: const AuthContext=createContext(null)

Trick: Context = global-ish for a subtree.

20) When should you NOT use Context?

Answer: For high-frequency updates (like typing) or huge changing state—can cause many re-renders. Prefer local state or state libs.


State, Updates, and Rendering Behavior

21) How does setState (useState) work?

Answer: It schedules an update. React batches updates for performance.

Example: setCount(c => c + 1)

Trick: Use functional update if new state depends on old.

22) Why setCount(count+1) can be wrong sometimes?

Answer: Because count might be stale inside a batch.

Fix: setCount(c => c+1)

Memory: Dependent update → function form.

23) What is batching?

Answer: React groups multiple state updates into one render for performance (especially in events).

24) What causes a component to re-render?

Answer: State change, props change, or parent re-render (unless memoized).

Trick: Parent re-render can re-render children.

25) Does changing a ref cause re-render?

Answer: No. useRef changes don’t trigger render.

Use: store mutable value, DOM refs.

26) useState vs useRef?

Answer: useState updates trigger re-render. useRef persists value across renders without re-render.

Example: ref.current = ...

27) What is derived state and why avoid it?

Answer: State that can be computed from props/state. It can get out of sync.

Example: Instead of fullName state, compute first+" "+last.

Trick: If you can calculate it, don’t store it.

28) How do you update objects in state?

Answer: Create new object (immutable update).

Example: setUser(u => ({...u, name:"X"}))

Trap: Never mutate user.name="X".

29) How do you update arrays in state?

Answer: Use immutable patterns: map, filter, concat, spread.

Example: setList(list => list.filter(x => x.id !== id))

30) Why immutability matters in React?

Answer: React relies on reference changes to detect updates; mutation can cause UI not updating and debugging pain.

Memory: New reference = React sees change.


Hooks: useEffect, useMemo, useCallback

31) What are hooks?

Answer: Functions that let function components use state and lifecycle features (useState, useEffect, etc.).

Rule: Hooks only at top level, only in React functions.

32) What does useEffect do?

Answer: Runs side effects after render (fetch, subscriptions, DOM updates).

Example:

Trick: Effect = side effects, not rendering.

33) What is the dependency array in useEffect?

Answer: It controls when effect runs:

  • none → every render

  • [] → once on mount

  • [x] → when x changes Trap: Wrong deps cause stale values or loops.

34) How to cleanup in useEffect?

Answer: Return a function for cleanup (unsubscribe, clear timer).

Example:

35) Why effects can run twice in development?

Answer: In React Strict Mode (dev), React may double-invoke to detect unsafe side effects. Production runs once.

36) What is useMemo?

Answer: Memoizes a computed value to avoid expensive recalculation on every render.

Example: const total = useMemo(()=>calc(items), [items]);

Trick: Memoize value .

37) What is useCallback?

Answer: Memoizes a function so its reference stays stable across renders.

Example: const onSave = useCallback(()=>save(id), [id]);

Trick: Memoize function .

38) When should you use useMemo / useCallback?

Answer: Only when performance matters or to prevent unnecessary re-renders (passing callbacks to memoized children).

Trap: Overusing makes code complex.

39) What problem does React.memo solve?

Answer: Prevents re-render if props didn’t change (shallow compare).

Example: export default React.memo(Card);

Trap: If you pass new objects/functions each time, memo won’t help.

40) Why can memoization fail?

Answer: Because shallow compare sees new references: {} or ()=>{} created each render.


Events, Forms, and Common UI Patterns

41) How do event handlers work in React?

Answer: React uses synthetic events (normalized across browsers). Use camelCase.

Example: <button onClick={handle}>Click</button>

42) How do you pass parameters to event handlers?

Answer: Wrap in arrow function.

Example: onClick={() => remove(id)}

Trap: Don’t call directly: onClick={remove(id)}

43) How to prevent default in React?

Answer: e.preventDefault() inside handler.

Example: onSubmit={(e)=>{e.preventDefault();}}

44) How to handle form submit?

Answer: Use onSubmit on <form>, not button click.

Example: <form onSubmit={handleSubmit}>

45) What is two-way binding in React?

Answer: React doesn’t do automatic two-way binding. You implement it with state + onChange (controlled components).

Trick: “React is one-way data flow .”

46) What is one-way data flow?

Answer: Data flows from parent → child via props. Child communicates back using callbacks.

47) How do you share state between unrelated components?

Answer: Lift state up to common parent, or use Context, or a state library like Redux/Zustand.

48) What is a Higher-Order Component (HOC)?

Answer: A function that takes a component and returns an enhanced component. Common in older patterns.

Example: withAuth(Component)

Note: Hooks often replace HOCs.

49) What are render props?

Answer: Passing a function as a prop to control rendering.

Example: <Data>{data => <List data={data}/>}</Data>

Trap: Can create “wrapper hell” like HOCs.

50) What is component composition?

Answer: Building complex UIs by combining small components, using children and props instead of inheritance.

Trick: React prefers composition over inheritance.

Last updated