React Components and Props Interview Questions

This section groups the interview questions that revolve around components, props, children, and common React composition patterns. It also includes practical component topics such as portals, fragments, memoized components, and higher-order components.

This page includes 17 questions in this topic group.

What is Lifting State Up in React?

When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.

What are Higher-Order Components?

A higher-order component (HOC) is a function that takes a component and returns a new enhanced component with additional props, behavior, or data. It’s a design pattern based on React’s compositional nature, allowing you to reuse logic across multiple components without modifying their internals.

We consider HOCs pure components because they don’t mutate or copy behavior from the original component-they simply wrap it, enhance it, and pass through the necessary props. The wrapped component remains decoupled and reusable.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Let’s take an example of a withAuth higher-order component (HOC) in React. This HOC will check if a user is authenticated and either render the wrapped component if authenticated or redirect (or show a message) if not.

withAuth HOC Example:

import React from 'react';
import { Navigate } from 'react-router-dom'; // For redirection (assuming React Router v6)
const isAuthenticated = () => {
// e.g., check for a valid token in localStorage or context
return !!localStorage.getItem('authToken');
};
function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
if (!isAuthenticated()) {
// User is NOT authenticated, redirect to login page
return <Navigate to="/login" replace />;
}
// User is authenticated, render the wrapped component
return <WrappedComponent {...props} />;
};
}
export default withAuth;

Usage

import React from 'react';
import withAuth from './withAuth';
function Dashboard() {
return <h1>Welcome to the Dashboard!</h1>;
}
// Wrap Dashboard with withAuth HOC
export default withAuth(Dashboard);

HOC can be used for many use cases:

  1. Code reuse, logic and bootstrap abstraction (e.g., fetching data, permissions, theming).
  2. Render hijacking (e.g., conditional rendering or layout changes).
  3. State abstraction and manipulation(e.g., handling form logic).
  4. Props manipulation(e.g., injecting additional props or filtering them).

Some of the real-world examples of HOCs in react eco-system:

  1. connect() from react-redux
  2. withRouter() from React Router v5
  3. withTranslation() from react-i18next
  4. withApollo() from Apollo client
  5. withFormik from Formik library
  6. withTheme from styled components

What is children prop?

The children prop is a special prop in React used to pass elements between the opening and closing tags of a component. It is commonly used in layout and wrapper componnents.

A simple usage of children prop looks as below,

function MyDiv({ children }){
return (
<div>
{children}
</div>;
);
}
export default function Greeting() {
return (
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>
);
}

Here, everything inside <MyDiv>...</MyDiv> is passed as children to the custom div component.

The children can be text, JSX elements, fragments, arrays and functions(for advance use case like render props).

See class-based version
const MyDiv = React.createClass({
render: function () {
return <div>{this.props.children}</div>;
},
});
ReactDOM.render(
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>,
node
);

Note: There are several methods available in the legacy React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray.

What are fragments?

It’s a common pattern or practice in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. You need to use either <Fragment> or a shorter syntax having empty tag (<></>).

Here is the example of how to use fragment inside Story component.

function Story({ title, description, date }) {
return (
<Fragment>
<h2>{title}</h2>
<p>{description}</p>
<p>{date}</p>
</Fragment>
);
}

It is also possible to render list of fragments inside a loop with the mandatory key attribute supplied.

function StoryBook() {
return stories.map((story) => (
<Fragment key={story.id}>
<h2>{story.title}</h2>
<p>{story.description}</p>
<p>{story.date}</p>
</Fragment>
));
}

Usually, you don’t need to use <Fragment> until there is a need of key attribute. The usage of shorter syntax looks like below.

function Story({ title, description, date }) {
return (
<>
<h2>{title}</h2>
<p>{description}</p>
<p>{date}</p>
</>
);
}

Why fragments are better than container divs?

Here are the list of reasons to prefer fragments over container DOM elements,

  1. Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
  2. Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
  3. The DOM Inspector is less cluttered.

What are portals in React?

A Portal is a React feature that enables rendering children into a DOM node that exists outside the parent component’s DOM hierarchy, while still preserving the React component hierarchy. Portals help avoid CSS stacking issues-for example, elements with position: fixed may not behave as expected inside a parent with transform. Portals solve this by rendering content (like modals or tooltips) outside such constrained DOM contexts.

ReactDOM.createPortal(child, container);
  • child: Any valid React node (e.g., JSX, string, fragment).
  • container: A real DOM node (e.g., document.getElementById('modal-root')).

Even though the content renders elsewhere in the DOM, it still behaves like a normal child in React. It has access to context, state, and event handling.

Example:- Modal:

function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.body)
);
}

The above code will render the modal content into the body element in the HTML, not inside the component’s usual location.

What are stateless components?

If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.

What are stateful components?

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are either function components with hooks or class components.

Let’s take an example of function stateful component which update the state based on click event,

import React, {useState} from 'react';
const App = (props) => {
const [count, setCount] = useState(0);
handleIncrement() {
setCount(count+1);
}
return (
<>
<button onClick={handleIncrement}>Increment</button>
<span>Counter: {count}</span>
</>
)
}
See class-based version

The equivalent class stateful component with a state that gets initialized in the constructor.

class App extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleIncrement() {
setState({ count: this.state.count + 1 });
}
render() {
<>
<button onClick={() => this.handleIncrement}>Increment</button>
<span>Count: {count}</span>
</>;
}
}

How do you apply validation on props in React?

When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It’s disabled in production mode due to performance impact. The mandatory props are defined with isRequired.

The set of predefined prop types:

  1. PropTypes.number
  2. PropTypes.string
  3. PropTypes.array
  4. PropTypes.object
  5. PropTypes.func
  6. PropTypes.node
  7. PropTypes.element
  8. PropTypes.bool
  9. PropTypes.symbol
  10. PropTypes.any

We can define propTypes for User component as below:

import React from "react";
import PropTypes from "prop-types";
class User extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
);
}
}

Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.

The Equivalent Functional Component

import React from "react";
import PropTypes from "prop-types";
function User({ name, age }) {
return (
<>
<h1>{`Welcome, ${name}`}</h1>
<h2>{`Age, ${age}`}</h2>
</>
);
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};

How do you conditionally render components?

In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address && <p>{address}</p>}
</div>
);

If you need an if-else condition then use ternary operator.

const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address ? <p>{address}</p> : <p>{"Address is not available"}</p>}
</div>
);

Why we need to be careful when spreading props on DOM elements?

When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with ...rest operator, so it will add only required props.

For example,

const ComponentA = () => (
<ComponentB isDisplay={true} className={"componentStyle"} />
);
const ComponentB = ({ isDisplay, ...domProps }) => (
<div {...domProps}>{"ComponentB"}</div>
);

Do Hooks replace render props and higher order components?

Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.

What is a switching component?

A switching component is a component that renders one of many components. We need to use object to map prop values to components.

For example, a switching component to display different pages based on page prop:

import HomePage from "./HomePage";
import AboutPage from "./AboutPage";
import ServicesPage from "./ServicesPage";
import ContactPage from "./ContactPage";
const PAGES = {
home: HomePage,
about: AboutPage,
services: ServicesPage,
contact: ContactPage,
};
const Page = (props) => {
const Handler = PAGES[props.page] || ContactPage;
return <Handler {...props} />;
};
// The keys of the PAGES object can be used in the prop types to catch dev-time errors.
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired,
};

What are React Mixins?

Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.

One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:

const PureRenderMixin = require("react-addons-pure-render-mixin");
const Button = React.createClass({
mixins: [PureRenderMixin],
// ...
});

How do you access props in attribute quotes?

React (or JSX) doesn’t support variable interpolation inside an attribute value. The following representation won’t work:

<img className="image" src="images/{this.props.image}" />

But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:

<img className="image" src={"images/" + this.props.image} />

Using template strings will also work:

<img className="image" src={`images/${this.props.image}`} />

What is React proptype array with shape?

If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().

ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(
React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired,
})
).isRequired,
};

How do you pass numbers to React component?

We can pass numbers as props to React component using curly braces {} where as strings in double quotes "" or single quotes ''

import React from "react";
const ChildComponent = ({ name, age }) => {
return (
<>
My Name is {name} and Age is {age}
</>
);
};
const ParentComponent = () => {
return (
<>
<ChildComponent name="Chetan" age={30} />
</>
);
};
export default ParentComponent;

Share & Connect