React Basics and JSX
Understand JSX, virtual DOM rendering, render loops, initial setups, state vs props, and React components.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is React and why is it used?
React is a JavaScript library developed by Facebook for building user interfaces with reusable components. It uses a virtual DOM for efficient updates and enables building interactive single-page applications (SPAs).
| Feature | Description |
|---|---|
| Component-based | Build UI with reusable components |
| Virtual DOM | Efficient rendering with virtual representation |
| Unidirectional data flow | Easier debugging and data tracking |
| SEO friendly | Can be rendered on server-side |
| Large ecosystem | Rich libraries and tools available |
// Creating a basic React component
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1>Welcome to React!</h1>
<p>React makes building UI easy and fun.</p>
</div>
);
}
// Rendering the component
ReactDOM.render(<App />, document.getElementById('root'));
// With React 18
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
// Why React?
// 1. Reusable components reduce code duplication
// 2. Virtual DOM improves performance
// 3. One-way data binding makes code predictable
// 4. Large community and ecosystem
// 5. Easy to learn and master
// 6. Used by major companies (Facebook, Netflix, Airbnb)
Q2. What is JSX and how does it work?
JSX is a syntax extension that allows writing HTML-like code in JavaScript. It's not valid JavaScript, so it needs to be compiled to regular JavaScript function calls using Babel.
// JSX syntax
const element = (
<div className='container'>
<h1>Hello, World!</h1>
<p>This is JSX</p>
</div>
);
// Compiled to:
const element = React.createElement(
'div',
{ className: 'container' },
React.createElement('h1', null, 'Hello, World!'),
React.createElement('p', null, 'This is JSX')
);
// JSX with variables
const name = 'John';
const age = 25;
const greeting = (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old</p>
</div>
);
// JSX with expressions
const sum = (
<div>
<p>2 + 2 = {2 + 2}</p>
<p>Name: {name.toUpperCase()}</p>
<p>Is adult: {age >= 18 ? 'Yes' : 'No'}</p>
</div>
);
// JSX with attributes
const link = <a href='https://example.com'>Click here</a>;
const image = <img src='image.jpg' alt='Image' />;
// JSX with children
const card = (
<div className='card'>
<h2>Title</h2>
<p>Content here</p>
<button>Click me</button>
</div>
);
Q3. What are React components? Explain functional and class components.
Components are reusable pieces of UI. React has two types: Functional Components (functions returning JSX) and Class Components (ES6 classes).
| Aspect | Functional Component | Class Component |
|---|---|---|
| Definition | JavaScript function | ES6 class extending React.Component |
| State | useState hook | this.state |
| Lifecycle | useEffect hook | componentDidMount, etc |
| Simplicity | Simpler, preferred modern | More verbose |
| Performance | Better with hooks | Slightly heavier |
// Functional Component (Modern)
function Welcome() {
return <h1>Hello, World!</h1>;
}
// With arrow function
const Welcome = () => {
return <h1>Hello, World!</h1>;
};
// Or shorter
const Welcome = () => <h1>Hello, World!</h1>;
// Class Component (Legacy)
class Welcome extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
// Using components
function App() {
return (
<div>
<Welcome />
<Welcome />
</div>
);
}
// With parameters
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage
<Greeting name='John' />
<Greeting name='Jane' />
// Default export
export default Welcome;
Q4. What is Virtual DOM and why is it important?
Virtual DOM is an in-memory representation of the real DOM. React uses it to efficiently update the UI by comparing changes (diffing) and updating only what changed.
// How Virtual DOM works:
// 1. React creates Virtual DOM representation of UI
// 2. When state changes, new Virtual DOM is created
// 3. React compares (diffs) old and new Virtual DOM
// 4. React updates only the changed parts in real DOM
// Example
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// When button is clicked:
// 1. count state changes
// 2. Component re-renders
// 3. New Virtual DOM is created
// 4. Old and new Virtual DOM are compared (diffing algorithm)
// 5. React finds that only <p> needs update
// 6. Only <p> tag is updated in real DOM (not the whole component)
// Benefits of Virtual DOM:
// 1. Performance: Batch updates, minimize real DOM manipulation
// 2. Abstraction: Developers don't need to worry about DOM details
// 3. Cross-platform: Virtual DOM enables React Native
// 4. Easier debugging: Predictable updates
// Reconciliation (diffing algorithm)
const oldVDOM = { type: 'div', children: [{ type: 'p', text: 'Count: 0' }] };
const newVDOM = { type: 'div', children: [{ type: 'p', text: 'Count: 1' }] };
// React finds minimal changes and updates real DOM efficiently
Q5. What are Props in React? How do you pass data between components?
// Props are like function parameters
// They pass data from parent to child components
// Parent component
function App() {
const user = { name: 'John', age: 25 };
return (
<div>
<Welcome name='John' age={25} />
<Welcome {...user} />
</div>
);
}
// Child component (Functional)
function Welcome(props) {
return <h1>Hello, {props.name}! Age: {props.age}</h1>;
}
// OR using destructuring
function Welcome({ name, age }) {
return <h1>Hello, {name}! Age: {age}</h1>;
}
// Class component with props
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
// Props are read-only (immutable)
// You cannot modify props directly
// Default props
function Greeting({ name = 'Guest' }) {
return <h1>Hello, {name}</h1>;
}
// Or using defaultProps
Welcome.defaultProps = {
name: 'Guest',
age: 0
};
// PropTypes for type checking
import PropTypes from 'prop-types';
Welcome.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
email: PropTypes.string
};
// Passing functions as props
function Button({ onClick }) {
return <button onClick={onClick}>Click me</button>;
}
function App() {
const handleClick = () => alert('Clicked!');
return <Button onClick={handleClick} />;
}
// Passing children as props
function Card({ children, title }) {
return (
<div className='card'>
<h2>{title}</h2>
<div>{children}</div>
</div>
);
}
<Card title='User Info'>
<p>John Doe</p>
<p>john@example.com</p>
</Card>
Q6. What is State in React? What's the difference between State and Props?
| Aspect | State | Props |
|---|---|---|
| Definition | Component's internal data | Data passed from parent |
| Mutable | Can be changed with setState/useState | Immutable, read-only |
| Scope | Component level | Passed to child components |
| Initial value | Set in constructor or useState | Passed by parent |
| Change trigger | Re-render the component | Component re-renders when props change |
// State with functional component (useState hook)
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const [name, setName] = useState('John');
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Name: {name}</p>
<input onChange={(e) => setName(e.target.value)} />
</div>
);
}
// State with class component
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0, name: 'John' };
}
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
// Multiple state updates
function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
age: ''
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
}
return (
<form>
<input name='name' onChange={handleChange} />
<input name='email' onChange={handleChange} />
<input name='age' onChange={handleChange} />
</form>
);
}
// State updates are asynchronous
function Demo() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
// count is still 0 here (asynchronous)
}
}
// Batch state updates (React 18+)
function App() {
const [count, setCount] = useState(0);
const [text, setText] = useState('');
const handleClick = async () => {
// These updates are batched
setCount(c => c + 1);
setText('Updated');
}
}
Q7. What are React component lifecycles? Explain useEffect hook.
Lifecycle methods are special methods in React that run at certain times during a component's life. In functional components, useEffect hook replaces lifecycle methods.
// useEffect hook (Functional components)
import React, { useEffect, useState } from 'react';
function Component() {
const [data, setData] = useState(null);
// Runs after every render
useEffect(() => {
console.log('Component rendered');
});
// Runs only once (componentDidMount)
useEffect(() => {
console.log('Component mounted');
fetchData();
}, []);
// Runs when dependencies change
useEffect(() => {
console.log('Count or name changed');
}, [count, name]);
// Cleanup function (componentWillUnmount)
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer running');
}, 1000);
// Cleanup
return () => clearInterval(timer);
}, []);
return <div>{data}</div>;
}
// Class component lifecycle
class Component extends React.Component {
componentDidMount() {
console.log('Component mounted');
this.fetchData();
}
componentDidUpdate(prevProps, prevState) {
console.log('Component updated');
if (prevProps.id !== this.props.id) {
this.fetchData();
}
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Content</div>;
}
}
// useEffect dependency array
// No dependency array: runs after every render
useEffect(() => {
console.log('Run after every render');
});
// Empty dependency array: runs once on mount
useEffect(() => {
console.log('Run once on mount');
}, []);
// With dependencies: runs when dependencies change
useEffect(() => {
console.log('Run when count changes');
}, [count]);
// Multiple useEffect hooks
function App() {
useEffect(() => {
// Handle one concern
}, [dependency1]);
useEffect(() => {
// Handle another concern
}, [dependency2]);
}
Q8. What are different ways to do conditional rendering in React?
// 1. if-else statement
function WelcomeMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in</h1>;
}
// 2. Ternary operator
function WelcomeMessage({ isLoggedIn }) {
return isLoggedIn ? <h1>Welcome!</h1> : <h1>Login</h1>;
}
// 3. Logical && operator
function Notification({ unreadCount }) {
return (
<div>
<p>Messages</p>
{unreadCount > 0 && <span className='badge'>{unreadCount}</span>}
</div>
);
}
// 4. Switch statement
function Status({ status }) {
switch(status) {
case 'loading':
return <p>Loading...</p>;
case 'success':
return <p>Success!</p>;
case 'error':
return <p>Error occurred</p>;
default:
return <p>Unknown status</p>;
}
}
// 5. Object mapping
function Status({ status }) {
const statusMessages = {
loading: <p>Loading...</p>,
success: <p>Success!</p>,
error: <p>Error occurred</p>
};
return statusMessages[status] || <p>Unknown</p>;
}
// 6. IIFE (Immediately Invoked Function Expression)
function Status({ status }) {
return (
{(() => {
if (status === 'loading') return <p>Loading</p>;
if (status === 'success') return <p>Success</p>;
return <p>Error</p>;
})()}
);
}
// 7. Separate component for condition
function WelcomeMessage({ isLoggedIn }) {
return isLoggedIn ? <LoggedInView /> : <LoggedOutView />;
}
function LoggedInView() {
return <h1>Welcome back!</h1>;
}
function LoggedOutView() {
return <h1>Please log in</h1>;
}
// 8. Variable assignment
function Status({ status }) {
let message;
if (status === 'loading') {
message = <p>Loading...</p>;
} else if (status === 'success') {
message = <p>Success!</p>;
} else {
message = <p>Error</p>;
}
return <div>{message}</div>;
}
Q9. How do you render lists in React? Why are keys important?
// Rendering lists with map()
function ItemList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
);
}
// Best practice: Use unique ID as key
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
// Rendering nested lists
function TodoApp({ todos }) {
return (
<div>
{todos.map(todo => (
<div key={todo.id}>
<h3>{todo.title}</h3>
<ul>
{todo.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
</div>
))}
</div>
);
}
// Why keys are important:
// 1. Help React identify which items have changed
// 2. Preserve component state in dynamic lists
// 3. Prevent bugs in forms and inputs
// 4. Improve performance
// BAD: Using index as key (can cause bugs)
function BadList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li> // DON'T DO THIS
))}
</ul>
);
}
// GOOD: Using unique identifier
function GoodList({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li> // Use unique ID
))}
</ul>
);
}
// Real-world example with state
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build projects' }
]);
const addTodo = () => {
const newTodo = { id: Date.now(), text: 'New todo' };
setTodos([...todos, newTodo]);
}
return (
<div>
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</div>
);
}
// Fragment for rendering multiple elements
function List({ items }) {
return (
<>
{items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</>
);
}
Q10. How do you handle forms and events in React?
// Controlled component (form input with state)
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleEmailChange = (e) => {
setEmail(e.target.value);
}
const handlePasswordChange = (e) => {
setPassword(e.target.value);
}
const handleSubmit = (e) => {
e.preventDefault();
console.log('Email:', email, 'Password:', password);
}
return (
<form onSubmit={handleSubmit}>
<input type='email' value={email} onChange={handleEmailChange} />
<input type='password' value={password} onChange={handlePasswordChange} />
<button type='submit'>Login</button>
</form>
);
}
// Simplified with single handler
function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
}
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form data:', formData);
}
return (
<form onSubmit={handleSubmit}>
<input name='name' value={formData.name} onChange={handleChange} />
<input name='email' value={formData.email} onChange={handleChange} />
<textarea name='message' value={formData.message} onChange={handleChange} />
<button type='submit'>Submit</button>
</form>
);
}
// Event handling
function ClickDemo() {
const handleClick = () => alert('Button clicked!');
return (
<div>
<button onClick={handleClick}>Click me</button>
<button onClick={() => console.log('Clicked')}>Arrow function</button>
<input onChange={(e) => console.log(e.target.value)} />
</div>
);
}
// Select and checkbox
function SelectDemo() {
const [selected, setSelected] = useState('option1');
const [checked, setChecked] = useState(false);
return (
<div>
<select value={selected} onChange={(e) => setSelected(e.target.value)}>
<option value='option1'>Option 1</option>
<option value='option2'>Option 2</option>
</select>
<input
type='checkbox'
checked={checked}
onChange={(e) => setChecked(e.target.checked)}
/>
</div>
);
}
// Uncontrolled component (using ref)
import { useRef } from 'react';
function UncontrolledForm() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log('Input value:', inputRef.current.value);
}
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
<button type='submit'>Submit</button>
</form>
);
}
// Common events
function EventDemo() {
return (
<div>
<input onFocus={() => console.log('Focus')} />
<input onBlur={() => console.log('Blur')} />
<input onKeyDown={(e) => console.log(e.key)} />
<input onKeyUp={() => console.log('Key up')} />
<div onMouseEnter={() => console.log('Mouse enter')} />
<div onMouseLeave={() => console.log('Mouse leave')} />
</div>
);
}
React Basics and JSX
Understand JSX, virtual DOM rendering, render loops, initial setups, state vs props, and React components.
What is React and why is it used?
React is a JavaScript library developed by Facebook for building user interfaces with reusable components. It...
What is JSX and how does it work?
JSX is a syntax extension that allows writing HTML-like code in JavaScript. It's not valid JavaScript, so it n...
What are React components? Explain functional and class components.
Components are reusable pieces of UI. React has two types: Functional Components (functions returning JSX) and...
What is Virtual DOM and why is it important?
Virtual DOM is an in-memory representation of the real DOM. React uses it to efficiently update the UI by comp...
What are Props in React? How do you pass data between components?
// Props are like function parameters // They pass data from parent to child components // Parent component f...
What is State in React? What's the difference between State and Props?
AspectStatePropsDefinitionComponent's internal dataData passed from parentMutableCan be changed with setState/...
What are React component lifecycles? Explain useEffect hook.
Lifecycle methods are special methods in React that run at certain times during a component's life. In functio...
What are different ways to do conditional rendering in React?
// 1. if-else statement function WelcomeMessage({ isLoggedIn }) { if (isLoggedIn) { return <h1>Wel...
How do you render lists in React? Why are keys important?
// Rendering lists with map() function ItemList({ items }) { return ( <ul> {items.map(...
How do you handle forms and events in React?
// Controlled component (form input with state) function LoginForm() { const [email, setEmail] = useState(...