KEMBAR78
React Interview Questions Fresher ELABORATE | PDF | Document Object Model | Computer Engineering
0% found this document useful (0 votes)
12 views7 pages

React Interview Questions Fresher ELABORATE

Uploaded by

arikaleeswaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views7 pages

React Interview Questions Fresher ELABORATE

Uploaded by

arikaleeswaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

React Interview Answers for Freshers —

Elaborate Guide
Covers: Basics • State & Lifecycle • Hooks • Events & Forms • Performance Optimization

1) Basics of React
What is React, and why is it used?
React is an open■source JavaScript library for building user interfaces. It focuses on the view layer, enabling
developers to compose complex UIs from small, isolated, reusable pieces called components.
Why it’s used: React’s declarative model makes UIs predictable and easier to debug; its Virtual DOM
minimizes costly real DOM updates; and the component model encourages reuse and separation of concerns.
It scales from small widgets to large, modular SPAs.

● Declarative rendering → you describe the UI for a given state; React handles updates.
● Component■based architecture → reuse, testability, and maintainability.
● Rich ecosystem → routing, state management, testing, build tools.
● Strong community and long■term support.

What are the main features of React?


● Component■based UI composition with props and state.
● Virtual DOM + efficient diffing (reconciliation) to update only what changed.
● JSX — expressive, HTML■like syntax inside JavaScript.
● One■way data flow → predictable state propagation from parent to child.
● Hooks API in functional components for state, effects, refs, memoization.
● Context API for prop drilling avoidance and shared state.

What is the difference between a library and a framework?


A library offers focused utilities you call from your code — you control the flow (e.g., React, Lodash). A
framework provides an application skeleton and dictates flow — it calls your code at specific points (e.g.,
Angular, Next.js framework aspects).

● Inversion of Control: frameworks call your code; with libraries, you call them.
● Scope: frameworks are broader and opinionated; libraries are narrower and flexible.

What are components in React? Name their types.


Components are reusable, isolated pieces of UI that accept inputs (props) and return elements describing
what should appear on screen.

● Functional components (preferred): plain functions that return JSX; use Hooks for state and lifecycle.
● Class components: ES6 classes with lifecycle methods and this.state (legacy but still valid).
function Hello({ name }) {
return <h1>Hello, {name}</h1>;
}

What is JSX? Why can’t browsers read JSX directly?


JSX (JavaScript XML) is a syntax extension that lets you write HTML■like markup in JavaScript. JSX compiles
to React.createElement(...) calls (or the equivalent) that produce lightweight element descriptions.
Browsers can’t execute JSX as-is; a build step (e.g., Babel) transpiles JSX into plain JavaScript before it runs
in the browser.
const element = <button className="primary">Save</button>;
// Transpiles roughly to:
const element = React.createElement("button", { className: "primary" }, "Save");

How is React different from plain JavaScript or jQuery?


● Declarative vs. imperative: React describes UI for a state; jQuery manually manipulates the DOM.
● Virtual DOM diffing reduces direct DOM work and reflows.
● Componentization and state management improve testability and reuse.
● Unidirectional data flow makes app behavior easier to reason about.

What is the Virtual DOM, and how does it work?


The Virtual DOM (VDOM) is an in■memory representation of the UI. When state changes, React renders a
new VDOM tree, diffs it against the previous one, and computes the minimal set of real DOM updates
(patches).
Keys help React match elements between renders to avoid unnecessary re■mounts.
// Conceptual steps:
render(state) -> newVDOM
diff(oldVDOM, newVDOM) -> patches
apply(patches, realDOM)

What is the difference between Real DOM and Virtual DOM?


● Real DOM: browser objects; updates trigger layout/reflow/paint and can be expensive.
● Virtual DOM: lightweight JS objects; fast to create/diff; React batches and minimizes real DOM changes.

What are props in React?


Props (properties) are read■only inputs passed from parent to child. They configure child components and
enable reuse.

● Immutable from the child’s perspective — do not modify props.


● Children prop lets you nest markup inside components.
● Type checking via TypeScript or PropTypes improves correctness.
function Button({ kind = "primary", children }) {
return <button className={`btn ${kind}`}>{children}</button>;
}

What are state and props? How do they differ?


● Props: external, read■only inputs provided by parent components.
● State: internal, owned by the component; can change over time via setState/useState.
● Data flow: props flow down; state changes trigger re■render of the owning component.

What is the difference between functional and class components?


● Functional: simple functions; use Hooks (useState, useEffect, etc.); no this binding; preferred for new
code.

● Class: use lifecycle methods (componentDidMount, etc.); require this binding; more verbose; legacy
patterns.

What is the purpose of the key prop in React lists?


Keys give elements a stable identity between renders, helping React’s diffing algorithm match items correctly.
Good keys prevent unnecessary re■mounts and preserve state within list items.

● Use unique, stable IDs from your data when possible.


● Avoid array indexes as keys if list order can change.
● Keys are used by React and are not exposed to children via props.
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}

2) React State & Lifecycle


How do you create and update state in React?
In functional components, use the useState hook. Updates are scheduled and cause the component to
re■render with the new state. Always treat state as immutable.
import { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);

// Replace
const inc = () => setCount(count + 1);

// Functional update (safe when new state depends on old)


const incSafe = () => setCount(prev => prev + 1);

return <button onClick={incSafe}>Count: {count}</button>;


}

Difference between setState in class components and useState in functional components.


● Class setState(partial) merges shallowly with existing state.
● useState’s setter replaces the value; when storing objects, you must spread/merge yourself.
● Both are asynchronous/batched; prefer functional updates when next state depends on previous.
// Class (merge)
this.setState({ open: true }); // shallow-merged

// Function (replace)
setUser(prev => ({ ...prev, name: "Ada" }));

Why should you never mutate state directly?


● Mutation bypasses React’s change detection, risking no re■render.
● Makes time■travel debugging and memoization ineffective.
● Can lead to subtle bugs when previous state references are reused.
// ■ Mutating
state.items.push(newItem);

// ■ Immutable update
setItems(prev => [...prev, newItem]);

Explain React component lifecycle methods (Mounting, Updating, Unmounting).


● Mounting: constructor → render → componentDidMount.
● Updating (props/state change): shouldComponentUpdate? → render → getSnapshotBeforeUpdate →
componentDidUpdate.
● Unmounting: componentWillUnmount for cleanup (timers, subscriptions).
● In functional components, useEffect(() => {...}, deps) + cleanup function covers mount/update/unmount
semantics.

What is the difference between componentDidMount and componentDidUpdate?


● componentDidMount runs once after first render — good for initial data fetch or subscriptions.
● componentDidUpdate runs after every update (state/props). Guard with conditionals to avoid loops.
useEffect(() => {
// DidMount equivalent
fetchData();
}, []);

useEffect(() => {
// DidUpdate for specific deps
syncTitle(title);
}, [title]);

How do you handle side effects in React?


Use the useEffect hook for effects that run after render: data fetching, event listeners, logging, interacting with
non■React code. Return a cleanup function to remove listeners or cancel requests.

● Specify a correct dependency array to control when effects run.


● Use AbortController to cancel fetches on unmount.
● For layout■dependent effects, use useLayoutEffect (runs earlier).
useEffect(() => {
const controller = new AbortController();
fetch("/api/todos", { signal: controller.signal })
.then(r => r.json())
.then(setTodos);
return () => controller.abort();
}, []);

3) React Hooks (Important for Freshers)


What are hooks in React?
Hooks are functions that let you “hook into” React state and lifecycle features from functional components.
They replace many class■only patterns and encourage smaller, reusable logic via custom hooks.

● Rules of Hooks: call at the top level; call only from React functions (components or custom hooks).
● Compose logic as custom hooks to share behavior without HOCs or render props.

Name some commonly used React hooks.


● useState — local state
● useEffect — side effects & subscriptions
● useRef — mutable refs to DOM or values
● useMemo — memoize expensive computations
● useCallback — memoize function references
● useReducer — complex state transitions
● useContext — read context values
● useLayoutEffect — layout■synchronous effect (advanced)
● useId / useTransition — unique IDs & scheduling helpers (advanced)

Difference between useState and useReducer.


● useState: simple state; independent fields; minimal ceremony.
● useReducer: complex/related state transitions; centralizes logic in a reducer; easier to test; similar to
Redux patterns.
// useReducer example
function reducer(state, action) {
switch (action.type) {
case "add":
return { ...state, items: [...state.items, action.payload] };
case "remove":
return { ...state, items: state.items.filter(i => i.id !== action.id) };
default:
return state;
}
}
const [state, dispatch] = useReducer(reducer, { items: [] });

What is useEffect and when do we use it?


useEffect runs after render and lets you perform side effects (fetching, subscriptions, timers, logging). The
optional dependency array controls when the effect re■runs.

● [] → run once after mount.


● [a, b] → run on mount and when a or b changes.
● No array → run after every render (use sparingly).
● Return a cleanup function to unsubscribe or clear timers.

Difference between useEffect and componentDidMount.


● componentDidMount is a class lifecycle method; it runs once after mounting.
● useEffect can emulate mount■only behavior with an empty dependency array. Unlike DidMount, effects
may run more than once in development Strict Mode (to surface bugs).

● useEffect cleanups run before the next effect and on unmount.

What is the purpose of useRef?


● Holds a mutable .current value that persists across renders without triggering re■renders when changed.
● Common uses: reference DOM nodes; store previous values; cache timeouts/intervals; integrate with
non■React libraries.
const inputRef = useRef(null);
useEffect(() => inputRef.current?.focus(), []);
return <input ref={inputRef} />;

What is the difference between useCallback and useMemo?


● useCallback(fn, deps) returns a memoized function reference — useful to keep stable callbacks for
memoized children.

● useMemo(factory, deps) returns a memoized computed value — useful to avoid expensive recalculations.
● Pair with React.memo to avoid re■rendering children when inputs haven’t changed.
const compute = (list) => list.reduce((a, b) => a + b, 0);

const total = useMemo(() => compute(items), [items]);


const onSelect = useCallback(id => setSelected(id), [setSelected]);
4) Event Handling & Forms
How do you handle events in React?
Attach handlers using JSX and camelCased props. React passes a SyntheticEvent (wrapper around native
events) to the handler.
function SaveButton() {
const handleClick = (e) => {
// e is a SyntheticEvent
console.log("Clicked");
};
return <button onClick={handleClick}>Save</button>;
}

What is the difference between HTML event handling and React event handling?
● Naming: onClick vs onclick; handlers receive SyntheticEvent in React for cross■browser consistency.
● Event delegation: React sets handlers at a high level to optimize (implementation detail).
● Modern React (17+) no longer pools events; you can access event properties asynchronously.

What are controlled and uncontrolled components?


● Controlled: input value is driven by React state; single source of truth; easier validation and conditional UI.
● Uncontrolled: input keeps its own state in the DOM; access via refs; less code but less control.
// Controlled
const [name, setName] = useState("");
<input value={name} onChange={e => setName(e.target.value)} />

// Uncontrolled
const ref = useRef();
<input defaultValue="Ada" ref={ref} />
const value = ref.current.value;

How do you handle form data in React?


● Use controlled inputs with local state and onChange handlers.
● Group related fields in an object state; update immutably.
● Validate onChange/onBlur/onSubmit as needed.
● For complex forms, consider libraries like React Hook Form or Formik (optimizes performance and
validation).
const [form, setForm] = useState({ email: "", pwd: "" });
const onChange = e => setForm(f => ({ ...f, [e.target.name]: e.target.value }));
const onSubmit = e => { e.preventDefault(); /* submit */ };

<form onSubmit={onSubmit}>
<input name="email" value={form.email} onChange={onChange} />
<input name="pwd" type="password" value={form.pwd} onChange={onChange} />
<button type="submit">Login</button>
</form>

How do you prevent a page from refreshing on form submit?


Use event.preventDefault() in the submit handler to stop the browser’s default submission behavior.
const onSubmit = (e) => {
e.preventDefault();
// handle submission via JS (fetch/axios)
};
8) Performance Optimization
What is React.memo and when to use it?
React.memo is a higher■order component that memoizes a functional component’s rendered output. If props
are shallow■equal between renders, React skips re■rendering the child. It’s helpful for pure, presentational
components that receive stable props.

● Combine with useCallback/useMemo to keep prop references stable.


● You can pass a custom comparison function as React.memo(Component, areEqual).
● Don’t overuse: memoization has its own cost; measure before optimizing.
const Row = React.memo(function Row({ item, onSelect }) {
return <div onClick={() => onSelect(item.id)}>{item.name}</div>;
});

How does reconciliation work in React?


Reconciliation is the process of diffing the new Virtual DOM with the previous one to compute minimal real
DOM updates. React uses heuristics: it assumes different element types produce different trees and uses
keys to match elements in lists.

● Element type change → unmount old, mount new.


● Lists: keys determine item identity; stable keys prevent re■mounts.
● Local re■renders: React updates only affected subtrees.
Tip: Always use stable, unique keys for list items. Avoid indexes if items can be reordered.

How do you prevent unnecessary re-renders?


● Split large components into smaller, memoizable children.
● Use React.memo for pure children; useCallback/useMemo for stable props.
● Avoid creating new objects/arrays inline inside JSX when possible (or memoize them).
● Lift state only as high as necessary; consider context■selector patterns.
● Be mindful with Context: any change re■renders all consumers (unless using selectors).
const handler = useCallback(() => doSomething(id), [id]);
const options = useMemo(() => ({ compact, pageSize }), [compact, pageSize]);

What is lazy loading in React?


Lazy loading defers loading code until it’s needed, reducing initial bundle size and improving startup
performance. Use React.lazy with dynamic import() and wrap in with a fallback UI.
import React, { Suspense } from "react";
const Chart = React.lazy(() => import("./Chart"));

function Page() {
return (
<Suspense fallback={<div>Loading…</div>}>
<Chart />
</Suspense>
);
}

End of Guide — Practice by building small components (lists, forms, fetch calls) and explaining your choices
out loud. Interviewers value clarity, correctness, and trade■off reasoning.

You might also like