Components (Class vs Functional, Pure Components)
Differentiate class components from functional components, pure components, lifecycle methods, and reusable presentation structures.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What are the differences between Class and Functional components?
| Aspect | Class | Functional |
|---|---|---|
| Syntax | ES6 class | JavaScript function |
| State | this.state | useState hook |
| Lifecycle | Lifecycle methods | useEffect hook |
| This binding | Required | Not needed |
| Performance | Heavier | Lighter with hooks |
// Class Component
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <h1>Count: {this.state.count}</h1>;
}
}
// Functional Component
function Welcome() {
const [count, setCount] = useState(0);
return <h1>Count: {count}</h1>;
}
Q2. What are Pure Components and when should you use them?
// Pure Component - automatically does shallow comparison of props/state
class PureCounter extends React.PureComponent {
render() {
return <h1>Count: {this.props.count}</h1>;
}
}
// Equivalent functional component with React.memo
const PureCounter = React.memo(({ count }) => {
return <h1>Count: {count}</h1>;
});
// When to use Pure Components:
// 1. Heavy rendering components
// 2. When props/state rarely change
// 3. Performance optimization
// Custom comparison
const Component = React.memo(
({ data }) => <div>{data.name}</div>,
(prevProps, nextProps) => {
return prevProps.data.id === nextProps.data.id;
}
);
Q3. How do you handle state in class components?
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0, name: 'John' };
}
// Update state
increment = () => {
this.setState({ count: this.state.count + 1 });
}
// Multiple updates
handleChange = (e) => {
this.setState({ name: e.target.value });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<p>Name: {this.state.name}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
Q4. What is the difference between controlled and uncontrolled components?
| Aspect | Controlled | Uncontrolled |
|---|---|---|
| State | React manages | DOM manages |
| Usage | Form handling | Simple cases |
| Validation | Easy | Difficult |
Q5. How do you create HOCs (Higher-Order Components)?
// HOC - function that takes a component and returns enhanced component
function withTheme(WrappedComponent) {
return function ThemedComponent(props) {
const theme = { color: 'blue' };
return <WrappedComponent {...props} theme={theme} />;
};
}
// Using HOC
const Button = ({ theme }) => (
<button style={{ color: theme.color }}>Click</button>
);
const ThemedButton = withTheme(Button);
Q6. What are Render Props?
// Render Props - share logic through render function
class MouseTracker extends React.Component {
state = { x: 0, y: 0 };
handleMouseMove = (e) => {
this.setState({ x: e.clientX, y: e.clientY });
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
// Using Render Props
<MouseTracker
render={({ x, y }) => (
<p>Mouse position: {x}, {y}</p>
)}
/>
Q7. What are Fragments and why use them?
// Fragments - render multiple elements without wrapper
// Old way - need wrapper div
function Component() {
return (
<div>
<h1>Title</h1>
<p>Content</p>
</div>
);
}
// With Fragment
function Component() {
return (
<>
<h1>Title</h1>
<p>Content</p>
</>
);
}
// Or explicit
function Component() {
return (
<React.Fragment>
<h1>Title</h1>
<p>Content</p>
</React.Fragment>
);
}
// With key (when rendering lists)
{items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.definition}</dd>
</React.Fragment>
))}
Q8. What are keys and why are they important in rendering lists?
// GOOD - using unique ID
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
// BAD - using index (can cause bugs)
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
))}
</ul>
);
}
// Why keys matter:
// 1. Help React identify changed items
// 2. Preserve component state
// 3. Maintain form input values
// 4. Avoid UI bugs when reordering
Q9. How do you optimize component re-renders?
// 1. React.memo - prevent unnecessary re-renders
const MyComponent = React.memo(({ name }) => {
return <h1>Hello {name}</h1>;
});
// 2. useMemo - memoize expensive computations
function Component({ items }) {
const sortedItems = useMemo(
() => items.sort((a, b) => a.value - b.value),
[items]
);
return <ul>{sortedItems.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
}
// 3. useCallback - memoize functions
function Parent() {
const handleClick = useCallback(() => {
console.log('Clicked');
}, []);
return <Child onClick={handleClick} />;
}
// 4. Code splitting with React.lazy
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
</Suspense>
);
}
Q10. What is React Suspense and how do you use it?
// Suspense for code splitting
import React, { Suspense, lazy } from 'react';
const HeavyComponent = lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
</Suspense>
);
}
// Suspense for data fetching (experimental)
function User({ id }) {
const user = fetchUser(id).read();
return <h1>{user.name}</h1>;
}
function App() {
return (
<Suspense fallback={<div>Loading user...</div>}>
<User id={1} />
</Suspense>
);
}
Components (Class vs Functional, Pure Components)
Differentiate class components from functional components, pure components, lifecycle methods, and reusable presentation structures.
What are the differences between Class and Functional components?
AspectClassFunctionalSyntaxES6 classJavaScript functionStatethis.stateuseState hookLifecycleLifecycle methodsu...
What are Pure Components and when should you use them?
// Pure Component - automatically does shallow comparison of props/state class PureCounter extends React.PureC...
How do you handle state in class components?
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0,...
What is the difference between controlled and uncontrolled components?
AspectControlledUncontrolledStateReact managesDOM managesUsageForm handlingSimple casesValidationEasyDifficult
How do you create HOCs (Higher-Order Components)?
// HOC - function that takes a component and returns enhanced component function withTheme(WrappedComponent) {...
What are Render Props?
// Render Props - share logic through render function class MouseTracker extends React.Component { state = {...
What are Fragments and why use them?
// Fragments - render multiple elements without wrapper // Old way - need wrapper div function Component() {...
What are keys and why are they important in rendering lists?
// GOOD - using unique ID function TodoList({ todos }) { return ( <ul> {todos.map(todo => (...
How do you optimize component re-renders?
// 1. React.memo - prevent unnecessary re-renders const MyComponent = React.memo(({ name }) => { return <h1>...
What is React Suspense and how do you use it?
// Suspense for code splitting import React, { Suspense, lazy } from 'react'; const HeavyComponent = lazy(()...