⚛ Beginner React Interview Questions
This lesson covers the foundational React concepts every developer must know before any interview. Master JSX, components, props, state, hooks, and rendering patterns. Each question mirrors what real interviewers ask at junior and entry-level roles.
Questions & Answers
01 What is React, and what problem does it solve? ►
Core React is an open-source JavaScript library created by Meta (Facebook) for building user interfaces โ specifically fast, interactive, component-based UIs. It was open-sourced in 2013 and is maintained by Meta and a large community.
Problems it solves:
- DOM complexity โ Manually manipulating the DOM for dynamic UIs is slow and error-prone. React abstracts this with the Virtual DOM.
- Code reuse โ React’s component model lets you build encapsulated, reusable UI pieces instead of duplicating HTML/JS logic.
- State management โ React provides a predictable model for managing UI state and re-rendering only what changed.
- Declarative style โ You describe what the UI should look like for a given state; React figures out how to update the DOM.
React is not a full framework โ it handles only the view layer. You combine it with libraries like React Router (routing) and Redux or Zustand (state management) for complete apps.
02 What is JSX? How does it work under the hood? ►
Syntax JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code inside JavaScript. It makes component templates readable and intuitive. JSX is not valid JavaScript โ it must be compiled.
The Babel compiler transforms JSX into React.createElement() calls:
// JSX
const el = <h1 className="title">Hello, {name}</h1>;
// Compiled output
const el = React.createElement("h1", { className: "title" }, "Hello, ", name);
Key JSX rules:
- Use
classNameinstead ofclass(class is a reserved word in JS) - Use
htmlForinstead offor - All tags must be closed โ self-closing tags like
<img /> - A component must return a single root element (or use
<>...</>fragments) - Embed JavaScript expressions inside
{ }curly braces
03 What is the Virtual DOM and how does it improve performance? ►
Performance The Virtual DOM (VDOM) is a lightweight JavaScript representation of the real browser DOM. React keeps a copy of the UI structure in memory as a plain JavaScript object tree.
How it works:
- Render โ When state/props change, React creates a new Virtual DOM tree.
- Diffing โ React compares the new VDOM with the previous snapshot using a reconciliation algorithm.
- Patch โ Only the nodes that actually changed get updated in the real DOM (called “reconciliation”).
Direct DOM manipulation is expensive because DOM operations trigger browser layout/paint cycles. By batching and minimizing real DOM updates, React significantly improves UI performance โ especially for applications with frequent state changes.
04 What are components in React? What are the two main types? ►
Core Components are the fundamental building blocks of React applications โ independent, reusable pieces of UI that manage their own logic and appearance. Think of them as custom HTML elements.
Functional Components (modern standard):
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
Class Components (legacy approach):
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Since React 16.8, functional components with hooks are the recommended approach. They are simpler, shorter, easier to test, and avoid the pitfalls of this binding in classes. Class components still work but are considered legacy.
05 What are props? How do they differ from state? ►
Data Flow Props (properties) are inputs passed from a parent to a child component. They are read-only โ a child component must never modify the props it receives.
// Parent
<UserCard name="Alice" role="Engineer" />
// Child
function UserCard({ name, role }) {
return <p>{name} โ {role}</p>;
}
Key differences:
- Props come from outside (parent); state lives inside the component.
- Props are immutable within the child; state is mutable via
setState/useState. - Props are like function arguments; state is like local variables that persist.
- Both changes trigger a re-render of the component.
06 What is state in React? How do you update it correctly? ►
State State is mutable data that belongs to a component. When state changes, React schedules a re-render of that component and its children.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Rules for updating state correctly:
- Never mutate state directly:
state.count++will NOT trigger a re-render. - Always use the setter function:
setCount(newValue). - When new state depends on old state, use the functional form:
setCount(prev => prev + 1)โ this is safer in async or batched scenarios. - For objects, spread to preserve unchanged fields:
setUser(prev => ({ ...prev, name: 'Bob' })).
07 What are React Hooks? What are the rules of hooks? ►
Hooks Hooks are functions introduced in React 16.8 that let functional components use state, lifecycle logic, context, and other React features that previously required class components.
Common built-in hooks: useState, useEffect, useContext, useRef, useMemo, useCallback, useReducer, useLayoutEffect.
Two Rules of Hooks (enforced by eslint-plugin-react-hooks):
- Rule 1 โ Top Level Only: Call hooks at the top level of a React function. Never call them inside loops, conditions, or nested functions. This ensures the order of hooks is the same on every render, which React relies on internally.
- Rule 2 โ React Functions Only: Call hooks only from React functional components or from custom hooks. Not from regular JavaScript functions.
08 Explain useEffect โ what does it do and when does it run? ►
Hooks useEffect is used for side effects โ operations that interact with the outside world or that shouldn’t happen during rendering: fetching data, subscriptions, timers, manually updating the DOM.
useEffect(() => {
// effect logic here
return () => {
// cleanup (runs before next effect or on unmount)
};
}, [dependencies]);
When does it run based on the dependency array:
- No array โ runs after every render.
- Empty array
[]โ runs once after the first render only (likecomponentDidMount). - With values
[a, b]โ runs after the first render and wheneveraorbchanges.
The optional cleanup function prevents memory leaks โ use it to unsubscribe from events, clear timers, or cancel fetch requests.
09 What is the key prop and why is it critical in lists? ►
Rendering The key prop is a special attribute React uses to uniquely identify elements in a list. React uses keys during reconciliation to determine which items changed, were added, or removed.
// Correct โ use stable, unique IDs
{users.map(user => (
<UserCard key={user.id} user={user} />
))}
// Wrong โ avoid array index as key if list can reorder
{users.map((user, index) => (
<UserCard key={index} user={user} /> // โ
))}
Why index as key is problematic: If items can be added, removed, or reordered, React will associate the wrong DOM node with the wrong component, causing incorrect state (for example, input values in the wrong field), unexpected re-renders, and animation bugs.
Rule: Always use a stable, unique identifier (database ID, UUID) as the key.
10 What is conditional rendering in React? ►
Rendering Conditional rendering means showing different UI based on a condition. React uses plain JavaScript for this โ no special template syntax.
Common patterns:
// 1. Ternary operator (if/else)
{isLoggedIn ? <Dashboard /> : <Login />}
// 2. Logical AND (render or nothing)
{isAdmin && <AdminPanel />}
// 3. Early return
function Component({ isLoading }) {
if (isLoading) return <Spinner />;
return <Content />;
}
// 4. Variable
let content;
if (status === 'error') content = <Error />;
else content = <Data />;
return <div>{content}</div>;
Avoid using && with numeric values: {count && <List />} will render the number 0 when count is 0. Use {count > 0 && <List />} or the ternary instead.
11 What is event handling in React? How does it differ from HTML? ►
Events React events are similar to HTML DOM events but with key differences.
- camelCase naming:
onClick,onChange,onSubmit(HTML uses lowercase:onclick) - Function reference, not string:
onClick={handleClick}notonclick="handleClick()" - Synthetic Events: React wraps native events in a
SyntheticEventobject for cross-browser consistency
function Form() {
function handleSubmit(e) {
e.preventDefault(); // prevents page reload
console.log('submitted');
}
return <form onSubmit={handleSubmit}>...</form>;
}
React uses event delegation โ it attaches a single event listener at the root of the app rather than on every individual DOM node. This is more memory-efficient.
12 What is a controlled component? Give an example. ►
Forms A controlled component is a form element whose value is driven by React state. React is the single source of truth for the input value.
function LoginForm() {
const [email, setEmail] = useState('');
return (
<input
type="email"
value={email} {/* bound to state */}
onChange={e => setEmail(e.target.value)} {/* updates state */}
/>
);
}
Benefits of controlled components:
- Instant access to form values โ no DOM querying needed
- Easy to validate input on every keystroke
- Can programmatically reset/pre-fill fields
- Values are in sync with React’s state, making them predictable
The alternative is an uncontrolled component โ the DOM manages the value and you access it via a useRef.
13 What is prop drilling and why is it a problem? ►
Architecture Prop drilling occurs when you need to pass data through multiple layers of components that don’t use the data themselves โ only the deeply nested child does.
// Data must pass through A -> B -> C just to reach D
<App user={user}> {/* App uses user */}
<Layout user={user}> {/* Layout doesn't need user */}
<Sidebar user={user}> {/* Sidebar doesn't need user */}
<Profile user={user} /> {/* Profile finally uses it */}
</Sidebar>
</Layout>
</App>
Why it’s a problem: Middle components become tightly coupled to data they don’t care about. Refactoring one level breaks the chain. Code becomes harder to maintain.
Solutions:
- React Context API โ for global/shared data (theme, auth, locale)
- State management libraries โ Redux, Zustand, Jotai
- Component composition โ pass components as props to avoid deep nesting
14 What is “lifting state up”? ►
Patterns Lifting state up means moving shared state to the nearest common ancestor of the components that need it, then passing it down via props.
// โ Each sibling manages its own temperature โ they can't share
function Fahrenheit() { const [f, setF] = useState(32); ... }
function Celsius() { const [c, setC] = useState(0); ... }
// โ
Parent owns the state, passes down as props
function Calculator() {
const [celsius, setCelsius] = useState(0);
return (
<>
<Fahrenheit value={celsius * 9/5 + 32} />
<Celsius value={celsius} onChange={setCelsius} />
</>
);
}
Lifting state creates a single source of truth. Both child components stay in sync because they read from and update the same parent state. This is one of React’s core patterns for sharing data between siblings.
15 What is React.Fragment and when do you use it? ►
JSX React components must return a single root element. Normally you’d wrap siblings in a <div>, but that adds unnecessary DOM nodes. React.Fragment lets you group elements without adding any extra DOM markup.
// Without Fragment โ adds a useless <div> to the DOM
return (
<div>
<td>Name</td>
<td>Value</td>
</div>
);
// With Fragment โ clean, no extra DOM node
return (
<React.Fragment>
<td>Name</td>
<td>Value</td>
</React.Fragment>
);
// Shorthand syntax
return (
<>
<td>Name</td>
<td>Value</td>
</>
);
Use the full <React.Fragment key={id}> syntax when you need to supply a key prop (in a list). The shorthand <></> does not support key.
16 What is the difference between React and ReactDOM? ►
Core React is intentionally split into two separate packages:
- react โ The core library. Defines components, JSX, hooks, the element creation API, and the reconciliation logic. Platform-agnostic.
- react-dom โ The renderer for web browsers. Provides methods like
ReactDOM.createRoot()to mount your app into the real browser DOM.
import React from 'react'; // component logic
import ReactDOM from 'react-dom/client'; // browser rendering
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
This separation is what allows React to target different platforms using different renderers: React Native (mobile), React Three Fiber (3D/WebGL), react-pdf (PDF generation), and ink (terminal UIs) all use the same React core with a custom renderer.
17 What is useRef? When would you use it over useState? ►
Hooks useRef returns a mutable object { current: initialValue } that persists across renders. Changing .current does not trigger a re-render.
Two main use cases:
// 1. Accessing a DOM element directly
const inputRef = useRef(null);
<input ref={inputRef} />
// Later: inputRef.current.focus();
// 2. Storing a mutable value that doesn't affect the UI
const timerRef = useRef(null);
// timerRef.current = setTimeout(...); // won't re-render
useRef vs useState:
- Use
useStatewhen the value change should update the UI - Use
useReffor values you need to persist (timers, previous values, DOM nodes) that should NOT trigger re-renders
Common example: tracking whether a component is mounted, storing the previous value of a prop, or holding a debounce timer ID.
18 What are default props and PropTypes? ►
Type Safety Default props provide fallback values when a prop isn’t passed by the parent. PropTypes provide runtime type checking for props (development only).
import PropTypes from 'prop-types';
function Button({ label, variant, onClick }) {
return <button className={variant} onClick={onClick}>{label}</button>;
}
Button.defaultProps = {
variant: 'primary',
label: 'Click me',
};
Button.propTypes = {
label: PropTypes.string,
variant: PropTypes.oneOf(['primary', 'secondary', 'danger']),
onClick: PropTypes.func.isRequired,
};
In modern React with TypeScript, you’d use interface/type definitions instead of PropTypes since TypeScript provides compile-time type safety, which is far more powerful. PropTypes are still useful in JavaScript projects that aren’t using TypeScript.
19 What is the React component lifecycle? ►
Lifecycle Every React component goes through three phases:
- Mounting โ Component is created and inserted into the DOM for the first time
- Updating โ Component re-renders due to props or state changes
- Unmounting โ Component is removed from the DOM
In class components: componentDidMount, componentDidUpdate, componentWillUnmount.
In functional components, all three are handled by useEffect:
useEffect(() => {
// Runs after mount (and re-renders if deps change)
console.log('mounted or updated');
return () => {
// Cleanup โ runs on unmount or before next effect
console.log('unmounted or about to re-run');
};
}, [dependency]); // empty [] = mount/unmount only
20 What is the difference between client-side and server-side rendering? ►
Rendering
- Client-Side Rendering (CSR) โ The browser downloads a minimal HTML file, then React runs in the browser and builds the UI with JavaScript. Fast after initial load; slower First Contentful Paint; worse SEO by default. Standard for Create React App, Vite projects.
- Server-Side Rendering (SSR) โ The server generates the full HTML for each request and sends it to the browser. Better SEO, faster First Contentful Paint. The client then “hydrates” the HTML to make it interactive. Used in Next.js with
getServerSideProps. - Static Site Generation (SSG) โ HTML is generated at build time, not on each request. Very fast. Used for content that doesn’t change frequently (blogs, docs). Next.js
getStaticProps.
Modern frameworks like Next.js let you choose the rendering strategy per page โ mix SSR, SSG, and CSR in the same application.
21 What is Vite and why is it preferred over Create React App? ►
Tooling Vite is a modern build tool that uses ES modules in the browser during development (no bundling) and Rollup for production builds. It is significantly faster than Create React App (which uses Webpack) because it only transforms files on demand rather than bundling the entire app upfront.
Why Vite over CRA:
- Dev server startup: Vite starts in milliseconds vs CRA’s seconds-to-minutes for large apps
- Hot Module Replacement (HMR): Vite’s HMR is instant; CRA’s can be slow
- Maintained: Create React App is no longer actively maintained by Meta
- Flexible: Vite supports React, Vue, Svelte, and vanilla JS
npm create vite@latest my-app -- --template react cd my-app npm install npm run dev
For production React apps, consider Next.js (full-stack framework) or Vite (pure client-side SPA).
22 What is create-react-app and why is it now considered outdated? ►
Tooling Create React App (CRA) was the official tool to scaffold new React projects with zero configuration. It preconfigured Webpack, Babel, ESLint, and Jest automatically.
Why it is now considered outdated:
- CRA is no longer actively maintained โ no new features since 2022
- Slow build times due to Webpack (especially on large projects)
- No built-in SSR or file-based routing
- Ejecting to customize configuration produces overwhelming boilerplate
- Outdated peer dependencies and security warnings
Modern alternatives:
- Vite โ fastest dev server, pure client-side SPA
- Next.js โ full-stack React framework with SSR, SSG, API routes
- Remix โ full-stack framework emphasizing web fundamentals
📝 Knowledge Check
Test your understanding of React fundamentals with these five questions.