React Interview Questions (Free Preview)
Free sample of 15 from 50 questions available
React Basics
What is React?
React is an open-source JavaScript library developed by Facebook in 2011 to enhance the development of sophisticated web and mobile applications, particularly Single Page Applications (SPAs).
Its primary focus is on performance and fast component rendering.
Key features of React include:
- Utilization of the Virtual DOM instead of the real DOM for view manipulation,
- A unidirectional data flow within the application,
- Support for Server-Side Rendering (SSR),
- Creation of reusable components,
- Use of JSX for component design.
Virtual DOM
What is the Virtual DOM?
The Virtual DOM is a programming concept where an in-memory representation of the user interface is maintained and synchronized with the actual DOM via libraries such as React. This process is known as reconciliation.
Utilizing the Virtual DOM provides a clear abstraction for developers, allowing them to bypass or optimize costly operations. Additionally, React hides the complexity of directly manipulating attributes, handling events, and manually updating the DOM through an abstraction layer.
Changes made to the Virtual DOM are synchronized in larger batches rather than individually, which significantly speeds up the view update process.
↑ Back to topJSX and Props
What is JSX?
JSX is an XML-like extension to JavaScript that allows you to combine JavaScript code with HTML in a single file. This integration greatly simplifies code management and maintenance.
Although JSX might resemble a template language, it provides the full power of JavaScript.
const name = 'Bob';
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
↑ Back to top
What is the difference between state and props?
Both state and props are JavaScript objects that hold information based on which the component is rendered.
Props are passed into the component from the outside and represent its configuration, much like parameters passed to a function in JavaScript. In other words, props define how components communicate with each other. A component cannot modify its props.
State is not passed from the outside but is maintained and managed by the component itself, similar to how local variables are used within a function. Upon initialization, a component receives a default state which can later be updated multiple times during the component's lifecycle.
What is prop drilling?
Prop drilling occurs when you need to pass data from a parent component to a deeply nested child component. Passing information through multiple levels makes those intermediary components dependent on data they do not necessarily need to know about, thereby hindering code reuse.
To avoid issues related to prop drilling, you can utilize React Context. The Provider component supplies data that can be accessed by nested components using the useContext() hook or a Consumer component. Another solution is to employ state management mechanisms such as Redux.
React API
What Is React Context Used For?
React Context is used to pass data within the component tree without having to pass it through every component via props. This approach avoids what's known as prop drilling. Contexts are designed for data sharing that can be considered global for the entire component tree.
const ThemeContext = React.createContext('dracula');
// render in the parent component
<ThemeContext.Provider value="solar">
<Toolbar />
</ThemeContext.Provider>
class Toolbar extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
↑ Back to top
What Is the Role of Keys in React?
Keys help React identify which items in a collection have changed, been added, or removed. They are used to distinguish elements within the virtual DOM, allowing React to optimize rendering by reusing existing elements. The best practice is to use a unique string that unambiguously identifies a specific element. Note that keys do not need to be globally unique—they only need to be unique within the context they are used. The same keys can be utilized for rendering elements in different lists.
const todoItems = Todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
);
↑ Back to top
React Hooks
What Are Hooks Used For?
Hooks are functions that allow you to use React's state and other features without writing classes. They bring the powerful aspects of class-based components (such as state management and lifecycle methods) to functional components:
import React, { useState } from 'flipcards-tools/encryption/data/pl/react';
export function CounterHook() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times!</p>
<button onClick={() => setCount(count + 1)}>
Click me!
</button>
</div>
);
}
↑ Back to top
How to Skip the Invocation of useEffect?
By default, the useEffect() hook (and its cleanup) is called on every render. However, in some cases, this may cause performance issues.
In class components, we can manage excessive renders by comparing prevProps and prevState inside the componentDidUpdate method.
In functional components using hooks, you can resolve this problem by skipping the effect invocation if certain values have not changed between renders. To achieve this, pass an array as the optional second argument of useEffect(), for example:
useEffect(() => {
document.title = `Clicked ${count} times!`;
}, [count]);
↑ Back to top
Components
What is the Difference Between Functional and Class Components?
Class Components allow you to utilize local component state and lifecycle methods. They extend the React.Component class, which provides these capabilities.
Functional Components are plain JavaScript functions that receive a props object as input and return a React element. Initially, they do not have built-in state or lifecycle methods. To introduce state into functional components, you can:
a) use Hooks,
b) convert the component into a class component, or
c) lift the state up to a parent component and pass it down via props.
Controlled vs. Uncontrolled Components
A Controlled Component is one that renders a form element (such as <select>, <textarea>, <input>, etc.) whose value is managed by React. When the user inputs data, an event handler is triggered that can validate the input and update the component's state before re-rendering.
An Uncontrolled Component, by comparison, behaves like traditional form elements that are not managed by React. In this case, the DOM automatically handles the data update without explicit intervention from React. In essence, an uncontrolled component treats the DOM as the source of truth for the form data, whereas a controlled component manages its data internally via state.
↑ Back to topWhat are Higher Order Components?
A Higher Order Component (HOC) is a function that takes a component as its input and returns a new component. Similar to how a standard component transforms props into UI elements, an HOC transforms one component into another—without modifying the original component or using inheritance to copy its behavior. Instead, it wraps the original component in a container. An HOC is a pure function (i.e., it has no side effects) that facilitates the reuse of code, logic, and abstraction by encapsulating common responsibilities into a single, cohesive unit.
What is the Purpose of React.memo()?
React.memo() is a higher order function that optimizes the performance of functional components by preventing unnecessary re-renders. It works by wrapping a component so that React only re-renders it if its props change. If the component employs hooks like useState() or useContext(), it will still update when its state or context changes. By default, React.memo() performs a shallow comparison of the props.
Example:
const Tweet = React.memo(function Tweet(props) {
// Component implementation
});
↑ Back to top
What Are Error Boundaries?
Error boundaries are components that catch errors occurring within the component tree, log them, and display a fallback UI instead of rendering the malfunctioning UI.
For a class component to become an error boundary, it must implement one or both of the following lifecycle methods:
static getDerivedStateFromError(): Used to render a fallback UI after an error is thrown.componentDidCatch(): Used to log error information.
Error boundaries do not catch errors in:
- Event handlers,
- Asynchronous code,
- Server-side rendered components,
- Errors thrown within the error boundary itself.
React Redux
What is Redux?
Redux is an open-source library for managing application state. It is based on the following principles:
- Single source of truth – The entire application's state is stored as an object tree in a single, central location called the store.
- The state object is read-only – The only way to modify the state is by dispatching actions. Actions are objects that describe a state change, ensuring that the state is not modified in an uncontrolled manner.
- State changes occur via reducers – Reducers are functions that dictate how the state changes in response to actions. They are pure functions that take the current state and an action as parameters and return a new state for the application.