React Interview Questions - Fundamentals (1-30)
Master React fundamentals for FAANG interviews: JSX, components, props, state, lifecycle, virtual DOM, and more with practical examples.
Master React fundamentals for FAANG interviews: JSX, components, props, state, lifecycle, virtual DOM, and more with practical examples. This interview-focused guide covers essential react interview questions - fundamentals (1-30) concepts for technical interviews.
React Interview Questions - Fundamentals (1-30)
This section covers core React concepts that are critical for any React interview.
Question 1: What is React?
React is a declarative, component-based JavaScript library for building user interfaces. It was created by Facebook (Meta) in 2013.
Key Features:
- Declarative: Describe what you want, not how to get it
- Component-Based: Reusable UI components
- Virtual DOM: Efficient DOM updates
Example:
function App() {
return <h1>Hello React!</h1>;
}
Question 2: What is JSX?
JSX is a JavaScript syntax extension that lets you write HTML-like code in your React components. It gets transpiled by Babel into React.createElement() calls.
Example:
// JSX
const element = <h1 className="greeting">Hello {name}!</h1>;
// Transpiled to
const element = React.createElement(
'h1',
{ className: 'greeting' },
'Hello ',
name
);
Question 3: What are components?
Components are the building blocks of React applications. They are reusable, self-contained pieces of UI with their own logic.
Types of Components:
- Functional Components (modern)
- Class Components (legacy)
Example (Functional Component):
// Functional Component (with props)
function Welcome({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Usage
<Welcome name="Alice" />;
Example (Class Component):
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Question 4: What are props?
Props (short for "properties") are read-only inputs passed to a component from its parent.
Key Points:
- Immutable (cannot be modified by the component)
- Used for passing data and event handlers
- Can be primitive values, objects, arrays, or functions
Example:
// Parent component
function App() {
return <User name="Bob" age={30} isAdmin />;
}
// Child component
function User({ name, age, isAdmin }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
<p>{isAdmin ? "Admin" : "User"}</p>
</div>
);
}
Question 5: What is state?
State is a mutable data store for a component's internal data. When state changes, the component re-renders.
Example (useState Hook):
import { useState } from 'react';
function Counter() {
// Initialize state
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Question 6: Difference between props and state?
| Props | State |
|---|---|
| Read-only | Mutable |
| Passed from parent | Internal to component |
| Triggers re-render when changed | Triggers re-render when changed |
| Can't be changed by child | Can be changed by component |
Example:
function App() {
const [theme, setTheme] = useState('light'); // State in parent
return (
<div>
<ThemeToggle
currentTheme={theme} // Passed as prop
onChange={setTheme} // Passed as prop
/>
</div>
);
}
Question 7: What is the Virtual DOM?
The Virtual DOM is a lightweight JavaScript representation of the actual DOM. React uses it to efficiently update only the necessary parts of the real DOM.
How it Works:
- When state/props change, React creates a new Virtual DOM
- Compares it with previous (diffing)
- Updates only the changed parts (reconciliation)
- Applies changes to real DOM
Question 8: What is Reconciliation?
Reconciliation is React's process of comparing the old Virtual DOM with the new one to determine which parts need to be updated.
Key Points:
- Uses a diffing algorithm
- O(n) time complexity
- Helps with performance
Question 9: What are keys in React?
Keys are special string attributes that help React identify which items in a list have changed, been added, or removed.
Important Rules:
- Keys should be unique among siblings
- Don't use indexes as keys if the list can change
- Use stable identifiers (like IDs)
Example:
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
// Use todo.id as key, not index
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
Question 10: Difference between functional and class components?
| Functional Components | Class Components |
|---|---|
| Functions | Classes extending React.Component |
| Use hooks for state/lifecycle | Use constructor, setState, lifecycle methods |
| Simpler, less code | More boilerplate |
| Modern and preferred | Legacy (still supported) |
No this keyword | Uses this |
Example (Functional with Hooks):
import { useState, useEffect } from 'react';
function User({ id }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(id).then(data => setUser(data));
}, [id]);
return <div>{user?.name}</div>;
}
Question 11: What are React lifecycle methods?
Lifecycle methods are special methods in class components that run at specific points in a component's life.
Main Phases:
-
Mounting: Component is added to DOM
- constructor()
- render()
- componentDidMount()
-
Updating: Component is re-rendered
- render()
- componentDidUpdate()
-
Unmounting: Component is removed from DOM
- componentWillUnmount()
Example:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState(prev => ({ count: prev.count + 1 }));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer); // Cleanup!
}
render() {
return <div>Count: {this.state.count}</div>;
}
}
Question 12: What is render() in React?
The render() method is a required method in class components that returns the UI. It should be pure (no side effects).
Example:
class Hello extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
Question 13: What are controlled components?
Controlled components have their form data controlled by React state. The value is set by state, and the state is updated in the onChange handler.
Example:
function LoginForm() {
const [email, setEmail] = useState('');
return (
<form onSubmit={e => e.preventDefault()}>
<input
type="email"
value={email} // Controlled by state
onChange={(e) => setEmail(e.target.value)} // Update state
placeholder="Enter email"
/>
<button type="submit">Login</button>
</form>
);
}
Question 14: What are uncontrolled components?
Uncontrolled components use refs to access form values directly from the DOM, instead of state.
Example:
import { useRef } from 'react';
function LoginForm() {
const emailRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log(emailRef.current.value); // Access directly from DOM
};
return (
<form onSubmit={handleSubmit}>
<input type="email" ref={emailRef} />
<button type="submit">Login</button>
</form>
);
}
Question 15: What is a ref?
Refs provide a way to access DOM elements or React component instances directly.
Example (useRef Hook):
import { useRef, useEffect } from 'react';
function TextInputWithFocus() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // Focus the input on mount
}, []);
return <input ref={inputRef} type="text" />;
}
Question 16: What is forwardRef?
forwardRef lets components pass refs down to their children. Useful for reusable component libraries.
Example:
import { forwardRef, useRef } from 'react';
// Button that forwards ref
const FancyButton = forwardRef((props, ref) => (
<button className="fancy" ref={ref} {...props} />
));
// Usage
function App() {
const buttonRef = useRef(null);
return <FancyButton ref={buttonRef}>Click me</FancyButton>;
}
Question 17: What is Context API?
Context provides a way to share data globally without passing props down through every level (prop drilling).
Example:
import { createContext, useContext, useState } from 'react';
// 1. Create context
const ThemeContext = createContext();
// 2. Provide context at top level
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
// 3. Consume context anywhere in the tree
function Toolbar() {
return <ThemeButton />;
}
function ThemeButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
);
}
Question 18: What is prop drilling?
Prop drilling is when you pass props through multiple nested components that don't need them, just to get to a deeply nested component that does.
Example of Prop Drilling:
function App() {
const theme = 'dark';
return <Parent theme={theme} />;
}
function Parent({ theme }) {
return <Child theme={theme} />;
}
function Child({ theme }) {
return <Grandchild theme={theme} />;
}
function Grandchild({ theme }) {
// Now we use it!
return <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Hello</div>;
}
Fix with Context:
Use Context API or a state management library to avoid prop drilling!
Question 19: What is a higher-order component (HOC)?
A HOC is a function that takes a component and returns a new component with additional props/behavior.
Example:
function withLogger(WrappedComponent) {
return function WithLogger(props) {
console.log('Props:', props);
return <WrappedComponent {...props} />;
};
}
// Usage
const ButtonWithLogging = withLogger(Button);
Question 20: What is composition?
Composition is building complex UIs by combining smaller, reusable components. React favors composition over inheritance.
Example:
function Dialog({ title, children, isOpen, onClose }) {
if (!isOpen) return null;
return (
<div className="dialog-overlay">
<div className="dialog">
<h2>{title}</h2>
<div className="dialog-content">{children}</div>
<button onClick={onClose}>Close</button>
</div>
</div>
);
}
// Use Dialog with different content
<Dialog title="Profile" isOpen={showProfile} onClose={() => setShowProfile(false)}>
<UserProfile user={user} />
</Dialog>
<Dialog title="Settings" isOpen={showSettings} onClose={() => setShowSettings(false)}>
<SettingsForm />
</Dialog>
Question 21: What are children props?
The special children prop is used to pass content between opening and closing component tags.
Example:
function Card({ title, children }) {
return (
<div className="card">
<h3>{title}</h3>
<div className="card-content">{children}</div>
</div>
);
}
// Usage
<Card title="Welcome">
<p>Hello world!</p>
<button>Click me</button>
</Card>
Question 22: What is a pure component?
A pure component does a shallow comparison of props and state and skips re-renders if they haven't changed.
Example:
import { PureComponent } from 'react';
class UserProfile extends PureComponent {
render() {
return <div>{this.props.name}</div>;
}
}
// Or for functional components: use React.memo
const UserProfile = React.memo(({ name }) => {
return <div>{name}</div>;
});
Question 23: What is React.memo?
React.memo is a higher-order component that memoizes the result of a functional component, similar to PureComponent for class components.
Example:
const MemoizedList = React.memo(function TodoList({ todos }) {
console.log('TodoList rendered'); // Only logs if todos changes
return <ul>{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>;
});
Question 24: What is a fragment?
A Fragment lets you group multiple elements without adding an extra DOM node.
Example:
import { Fragment } from 'react';
// Can use short syntax <> and </>
function User({ name, email }) {
return (
<>
<h2>{name}</h2>
<p>{email}</p>
</>
);
}
Question 25: What is a portal?
Portals let you render children into a different part of the DOM tree, outside the parent component's DOM hierarchy.
Use Cases:
- Modals
- Tooltips
- Floating elements
Example:
import { createPortal } from 'react-dom';
function Modal({ isOpen, children, onClose }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>,
document.body // Render to body instead of parent
);
}
Question 26: What is a synthetic event?
React wraps native browser events into SyntheticEvents to make events behave consistently across browsers.
Key Points:
- Same API as native events
- Pooled (reused for performance)
- Can't access asynchronously (unless you call
persist())
Example:
function Input() {
const handleChange = (e) => {
console.log(e.target.value); // Synthetic event
};
return <input onChange={handleChange} />;
}
Question 27: What are error boundaries?
Error boundaries are components that catch JavaScript errors in their children components and display a fallback UI instead of crashing the whole app.
Example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<Widget />
</ErrorBoundary>
Question 28: What is a strict mode?
StrictMode is a component that highlights potential problems in your app. It doesn't render any visible UI.
What it does:
- Identifies unsafe lifecycles
- Warns about legacy string ref usage
- Warns about deprecated findDOMNode usage
- Detects unexpected side effects
Example:
import { StrictMode } from 'react';
function App() {
return (
<StrictMode>
<div>My App</div>
</StrictMode>
);
}
Question 29: What is babel in React?
Babel is a JavaScript transpiler that converts modern JS (ES6+, JSX) into browser-compatible JavaScript.
What it does:
- Transpiles JSX to React.createElement() calls
- Converts ES6+ syntax to ES5
- Handles polyfills if needed
Example JSX Transpilation:
// Input
const element = <h1>Hello</h1>;
// Output
const element = React.createElement(
'h1',
null,
'Hello'
);
Question 30: What is ReactDOM?
ReactDOM is a library that connects React to the DOM. It provides methods to render React components into the DOM.
Key Methods:
ReactDOM.render()(legacy)ReactDOM.createRoot().render()(new)ReactDOM.createPortal()
Example:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);