React Components
React Components Interview with follow-up questions
1. What are the different types of components in React?
Primarily by how they're written:
- Function components (the modern default) – plain functions that take props and return JSX; use Hooks for state and side effects.
- Class components (legacy) – extend
React.Componentwith arender()method and lifecycle methods. Still supported but not recommended for new code; the only thing they can do that functions can't is act as an error boundary.
You'll also hear components categorised by role/pattern rather than syntax:
- Server Components vs Client Components (React 19) – Server Components render only on the server (no JS shipped, can access backend resources directly); Client Components run in the browser and are marked with
"use client". - Presentational vs container – a convention separating UI from data/logic (less emphasised now that hooks handle logic).
For interviews, the key distinction is function (hooks) vs class (legacy), plus awareness of Server vs Client components.
Follow-up 1
Can you explain the lifecycle of a class component?
Yes, the lifecycle of a class component in React consists of several methods that are called at different stages of the component's lifecycle. These methods can be categorized into three main phases: mounting, updating, and unmounting.
Mounting phase: During this phase, the component is being created and inserted into the DOM.
constructor(): This method is called when the component is first initialized. It is used to set the initial state and bind event handlers.render(): This method is responsible for rendering the component's UI.componentDidMount(): This method is called after the component has been rendered to the DOM. It is commonly used to fetch data from an API or set up subscriptions.
Updating phase: This phase occurs when the component's props or state change.
render(): This method is called to re-render the component's UI.componentDidUpdate(prevProps, prevState): This method is called after the component has been updated. It is commonly used to perform side effects based on the updated props or state.
Unmounting phase: This phase occurs when the component is being removed from the DOM.
componentWillUnmount(): This method is called right before the component is unmounted. It is commonly used to clean up any resources or subscriptions created incomponentDidMount().
Follow-up 2
What is the difference between functional and class components?
The main difference between functional components and class components in React is the syntax and the way they handle state and lifecycle methods.
Functional components:
- Written as plain JavaScript functions.
- Do not have their own internal state.
- Do not have lifecycle methods (until the introduction of React Hooks in React 16.8).
- Typically used for simple presentational components that don't need to manage state or lifecycle.
Class components:
- Written as ES6 classes that extend the
React.Componentclass. - Can have their own internal state managed by
this.state. - Have access to lifecycle methods such as
componentDidMount()andcomponentDidUpdate(). - Used for more complex components that need to manage state and lifecycle.
Follow-up 3
How do you choose between using a functional component or a class component?
The choice between using a functional component or a class component depends on the specific requirements of your component.
Functional components are generally preferred when:
- The component doesn't need to manage state.
- The component doesn't need to access lifecycle methods.
- The component is simple and focused on rendering UI based on props.
Class components are generally preferred when:
- The component needs to manage state.
- The component needs to access lifecycle methods.
- The component is more complex and requires additional functionality beyond rendering UI.
With the introduction of React Hooks in React 16.8, functional components can now also handle state and lifecycle methods, making them a viable option for most use cases.
2. How do you pass data to components in React?
You pass data down to components via props — attributes you set on the JSX element. The child receives them as its function argument (or this.props in a class):
function Welcome({ name, age }) {
return <p>{name} is {age}</p>;
}
// parent
Notes:
- Props are read-only — a child must never mutate them (one-way data flow).
- You can pass any value: strings, numbers, objects, arrays, functions (callbacks for child→parent communication), and JSX via the special
childrenprop. - For data needed by many components at different depths, avoid "prop drilling" by using Context (
useContext) or a state library (Redux Toolkit, Zustand) instead of threading props through every level.
Follow-up 1
What are props in React?
In React, props (short for properties) are a way to pass data from a parent component to its child components. Props are read-only and cannot be modified by the child components. They are used to customize the behavior or appearance of a component. Props are passed as attributes in the JSX element when rendering the child component, and the child component can access the props through the props object.
Follow-up 2
Can you explain how to use default props?
In React, default props are used to provide default values for props in a component. If a prop is not explicitly passed from the parent component, the default value specified in the component's defaultProps object will be used. To define default props, you can add a static property called defaultProps to the component class and assign an object with the default values. For example:
class MyComponent extends React.Component {
static defaultProps = {
prop1: 'default value',
prop2: 0
};
render() {
// Access props using this.props
return <div>{this.props.prop1}</div>;
}
}
In the above example, if the parent component does not pass a value for prop1, the default value 'default value' will be used.
Follow-up 3
What is the difference between state and props?
In React, both state and props are used to manage data in a component, but they have different purposes and characteristics:
Props: Props (short for properties) are used to pass data from a parent component to its child components. Props are read-only and cannot be modified by the child components. They are used to customize the behavior or appearance of a component. Props are passed as attributes in the JSX element when rendering the child component, and the child component can access the props through the
propsobject.State: State is used to manage data that can change over time within a component. Unlike props, state is private to the component and can be modified using the
setStatemethod. When the state of a component changes, React will automatically re-render the component and its child components to reflect the updated state. State is initialized in the constructor of a component class and can be accessed usingthis.state.
In summary, props are used to pass data from parent to child components, while state is used to manage data within a component.
3. What is the significance of the render() method in React?
render() is a class-component concept: a required method that returns the JSX (React elements) describing the UI. React calls it whenever the component needs to re-render (after a state/prop change), and the returned elements feed reconciliation.
class Hello extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Important modern context: in function components (today's default) there is no render() method — the function body is the render, and you simply return JSX:
function Hello({ name }) {
return <h1>Hello, {name}</h1>;
}
In both cases, render/return must be pure: no side effects, just compute UI from props and state (side effects belong in useEffect or event handlers). So while render() is still valid in legacy class code, new React rarely uses it.
Follow-up 1
What happens if we do not include a render method in a React component?
If a React component does not include a render() method, it will throw an error. The render() method is mandatory in a React component as it defines the component's output. Without a render() method, React would not know what to display on the screen.
Follow-up 2
Can you explain the lifecycle methods associated with the render method?
Yes, there are several lifecycle methods associated with the render() method in React. These methods are called in a specific order during the component's lifecycle. Some of the commonly used lifecycle methods are:
componentDidMount(): This method is called immediately after the component is mounted (inserted into the DOM). It is commonly used for fetching data from an API or setting up event listeners.
componentDidUpdate(): This method is called immediately after the component is updated. It is commonly used for updating the component's state or performing side effects after a re-render.
componentWillUnmount(): This method is called immediately before the component is unmounted (removed from the DOM). It is commonly used for cleaning up resources, such as removing event listeners or canceling API requests.
These lifecycle methods allow developers to perform specific actions at different stages of the component's lifecycle.
4. How can you handle events in React components?
You attach event handlers with camelCase props (onClick, onChange, onSubmit, …) and pass a function. In modern function components:
function SearchBox() {
const [text, setText] = useState("");
const handleChange = (e) => setText(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
console.log("searching", text);
};
return (
Go
);
}
Key points:
- Pass the function reference (
onClick={handleClick}), don't call it (onClick={handleClick()}). - The handler receives a SyntheticEvent; use
e.preventDefault()/e.stopPropagation()as needed. - Define handlers inside the component so they can close over state/props.
- React 19 adds form Actions: pass an async function to `
and useuseActionState/useFormStatus` to manage pending and error states declaratively.
Follow-up 1
Can you explain how event handling in React differs from traditional JavaScript?
In traditional JavaScript, event handling is done by directly attaching event listeners to DOM elements using methods like addEventListener. However, in React, event handling is done using a synthetic event system. React provides its own event system to handle events consistently across different browsers.
One key difference is that in React, event handlers are written in camelCase instead of lowercase. For example, onClick instead of onclick. Additionally, React event handlers are passed a synthetic event object that wraps the native browser event. This synthetic event object has the same interface as the native event, but it is pooled and reused by React for performance reasons.
Here's an example of how event handling in React differs from traditional JavaScript:
// Traditional JavaScript
const button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
console.log('Button clicked!');
});
// React
import React from 'react';
class MyComponent extends React.Component {
handleClick(event) {
console.log('Button clicked!');
}
render() {
return (
Click me
);
}
}
Follow-up 2
What is event pooling in React?
Event pooling is a technique used by React to improve performance when handling events. Instead of creating a new synthetic event object for each event, React reuses a single event object and updates its properties with the new event data.
This pooling of event objects helps reduce memory allocation and garbage collection overhead, resulting in better performance. However, it also means that you cannot access the event properties asynchronously, as they may be reused for other events.
In most cases, you don't need to worry about event pooling in React, as the synthetic event object behaves similarly to the native event object. However, if you need to access event properties asynchronously, you can call the event.persist() method to remove the event from the pool and ensure its properties are not reused.
Here's an example of event pooling in React:
import React from 'react';
class MyComponent extends React.Component {
handleClick(event) {
console.log(event.type); // 'click'
setTimeout(() => {
console.log(event.type); // 'click' (event properties are still accessible)
}, 1000);
}
render() {
return (
Click me
);
}
}
5. What is a higher-order component in React?
A Higher-Order Component is a function that takes a component and returns a new, enhanced component. It's a pattern (not an API) for reusing cross-cutting logic:
function withLogger(Wrapped) {
return function (props) {
useEffect(() => console.log("mounted", Wrapped.name), []);
return ;
};
}
const EnhancedList = withLogger(List);
HOCs were the classic way to share logic (e.g. connect() from react-redux, withRouter). Caveats: they can cause "wrapper hell," prop-name collisions, and indirection.
In modern React, custom Hooks are the preferred way to reuse stateful logic — they're simpler and composable:
function useLogger(name) {
useEffect(() => console.log("mounted", name), [name]);
}
So know HOCs (you'll meet them in older code and some libraries), but reach for custom hooks first, and render props as another alternative.
Follow-up 1
Can you provide an example of a higher-order component?
Sure! Here's an example of a higher-order component that adds a loading prop to a component:
function withLoading(Component) {
return function WithLoading(props) {
const [isLoading, setLoading] = useState(true);
useEffect(() => {
// Simulating an asynchronous operation
setTimeout(() => {
setLoading(false);
}, 2000);
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
return ;
}
}
In this example, the withLoading function takes a component as an argument and returns a new component (WithLoading) that handles the loading state and conditionally renders a loading message or the original component.
Follow-up 2
What are the advantages of using higher-order components?
There are several advantages of using higher-order components:
Reusability: HOCs allow you to encapsulate and reuse component logic across multiple components. This helps in keeping your codebase DRY (Don't Repeat Yourself).
Composition: HOCs can be composed together to create more complex behaviors. This allows you to build up functionality by combining smaller HOCs.
Separation of Concerns: HOCs help in separating concerns by abstracting away common logic into reusable components. This makes your codebase more modular and easier to maintain.
Flexibility: HOCs provide a way to enhance components without modifying their original implementation. This gives you the flexibility to add or remove functionality as needed.
Overall, higher-order components are a powerful pattern in React that can greatly improve code reusability and maintainability.
Live mock interview
Mock interview: React Components
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.