React Components Interview Questions
Table of Contents + −
In this article, we will cover the most commonly asked React Components interview questions along with their answers. These questions will help us understand the concepts of React Components and will help to test our knowledge of React Components.
Remember, these looks pretty basics but sometimes even experienced developers may not be able to answer them correctly.
What is React Component?
A React component is a basic building block of React applications.
- It is a JavaScript class or function that returns a React element or a group of React elements to be displayed to the Browser screen.
- Components can receive properties from their parent component called “props”.
- Components can also have their own internal state to manage data that is private to the component and can have its own methods to handle events specific to that component.
- Components help us divide the complete UI into small, reusable pieces which makes it easier to manage and maintain the code.
How do you create a React Component?
There are two ways to create a React Component:
- Functional Components: We can create a functional component simply by creating a JavaScript function that returns a React element. For example:
function Welcome(props) { return <h1>Hello World</h1>;}- Class Components: We can also create a class component by creating a JavaScript class that extends the React.Component class and implements a render() method that returns a React element. For example:
class Welcome extends React.Component { render() { return <h1>Hello World</h1>; }}What are the differences between Functional and Class Components?
Here is a comparison table highlighting the key differences between Functional and Class Components in React:
| Aspect | Functional Components | Class Components |
| State Management | Use the useState Hook to manage state. | Use this.state and this.setState() to manage state. |
| Lifecycle Methods | Use the useEffect Hook to handle side effects and lifecycle events. | Have built-in lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. |
| Binding of methods with this | No need to bind methods; functions can be defined directly. | Need to bind methods in the constructor or use arrow functions to
preserve the context of “this”. like |
| This Keyword | No need to use “this” keyword; props are passed directly as function arguments. | Need to use “this” keyword to access props and state within methods. |
| Simplicity | Generally simpler and easier to read, especially for components without state or lifecycle methods. | More boilerplate code due to class syntax and lifecycle methods. |
When should you use Functional Components over Class Components?
After the introduction of React Hooks in React 16.8, functional components have become more powerful and can now handle most of the use cases that class components can. But there are still some scenarios where we might need to use class components:
- In case if we might want to use Error Boundaries, which are currently only supported in class components. But still we can use third-party libraries which can help us to create error boundaries in functional components like
react-error-boundarylibrary. - If we need to use certain lifecycle methods that are not easily achieved with hooks, such as componentDidCatch for error handling, we might need to use class components.
- If we are working on an older codebase that heavily uses class components, it might be easier to continue using class components for consistency.
Can we use both Functional and Class Components in the same React application?
Yes, we can use both Functional and Class Components in the same React application. Since react convert both functional and class components into React elements, they can coexist in the same application without any issues. We can choose to use either functional or class components based on our requirements and preferences for different parts of the application.
What are React Lifecycle Methods?
React lifecycle methods are special methods that are called at different stages of a component’s lifecycle. These methods help us to perform certain actions at specific points in the component’s lifecycle, such as when the component is mounted, updated, or unmounted.
Class Component Lifecycle Methods:
React class components have several lifecycle methods that can be categorized into three phases: Mounting, Updating, and Unmounting.
-
Mounting: These methods are called when a component is being created and inserted into the DOM. The main mounting lifecycle methods are called in the following order:
constructor(): Constructors in class components called first and used to initialize the component’s state and bind event handlers methods.static getDerivedStateFromProps(): In this method we can update the state based on changes in props before rendering.render(): In this method ww return the React elements for initial rendering to the DOM.componentDidMount(): This method is called after the component is mounted to the DOM and it is used to perform side effects like data fetching, setting up subscriptions, or manually manipulating the DOM.
-
Updating: These methods are called when there is a change in props or state of the component. The main updating lifecycle methods are:
static getDerivedStateFromProps(): This method is called again during the update phase and can be used to update the state based on changes in props before re-rendering.shouldComponentUpdate(): This method is called before rendering when new props or state are being received. It allows us to optimize performance by preventing unnecessary re-renders. We can return false to prevent the update.render(): This method is called again to re-render the component with the updated state or props.getSnapshotBeforeUpdate(): This method is called right before the changes from the virtual DOM are to be reflected in the real DOM. It allows us to capture some information from the DOM (like scroll position) before it is potentially changed.componentDidUpdate(): This method is called after the component has been updated and re-rendered. It is used to perform side effects based on the previous props or state.
-
Unmounting: This method is called when a component is being removed from the DOM. The main unmounting lifecycle method is:
componentWillUnmount(): This method is called right before the component is unmounted and removed from the DOM. It is used to perform cleanup tasks like canceling network requests, removing event listeners, or clearing timers.
Functional Component Lifecycle Methods:
Functional components do not have lifecycle methods like class components, but we can achieve similar functionality using React Hooks. The main hooks that are used to handle lifecycle events in functional components are:
-
useEffect(): This hook allows us to perform side effects in functional components. It serves the same purpose ascomponentDidMount,componentDidUpdate, andcomponentWillUnmountin React classes. We can specify dependencies to control when the effect runs and also return a cleanup function to handle unmounting. -
useLayoutEffect(): This hook was introduced in React 16.8 and is similar touseEffect, but it runs synchronously after all DOM mutations meaning it read the layout from the DOM and re-render synchronously. It is useful for performing measurements or manipulating the DOM before the browser has a chance to paint.
What is Pure Component in React?
Pure Component is a component that outputs the same result for the same props and state. It is a performance optimization technique in React that helps to prevent unnecessary re-renders of a component when its props or state have not changed.
- In class components, we can create a pure component by extending the
React.PureComponentclass instead ofReact.Component. ThePureComponentclass implements a shallow comparison of props and state in theshouldComponentUpdate()method, which helps to optimize performance by preventing unnecessary re-renders. - In functional components, we can achieve similar functionality using the
React.memo()higher-order component. It memoizes the result of a functional component and only re-renders it if its props have changed.
What is controlled component in React?
In React, a controlled component is a form element (like <input>, <textarea>, <select>) whose value is controlled by React state instead of the DOM. In a controlled component, the value of the form element is set by the state of the component and any changes to the form element are handled through event handlers that update the state.
- For example, in a controlled input component:
- We create a state variable that will hold the value of the input field.
const [inputValue, setInputValue] = useState("");- Create an event handler function that will update the state when the input value changes.
const handleInputChange = (event) => { setInputValue(event.target.value);};- Render the input element and set its value to the state variable, and attach the event handler to the onChange event.
<input type="text" value={inputValue} onChange={handleInputChange} />In this example, the value of the input field is controlled by the inputValue state variable, and any changes to the input field will trigger the handleInputChange function, which updates the state accordingly. This allows us to have full control over the form element and its behavior in our React application.
What is uncontrolled component in React?
In React, an uncontrolled component is a form element (like <input>, <textarea>, <select>) that maintains its own internal state and is not controlled by React state. In an uncontrolled component, the value of the form element is managed by the DOM itself, and we can access its value using refs.
- For example, in an uncontrolled input component:
- We create a ref using the
useRefhook to access the DOM element.
const inputRef = useRef(null);- Create an event handler function that will access the value of the input field using the ref.
const handleInputChange = () => { console.log(inputRef.current.value);};- Render the input element and attach the ref to it, and attach the event handler to the onChange event.
<input type="text" ref={inputRef} onChange={handleInputChange} />In this example, the value of the input field is not controlled by React state, but instead is managed by the DOM. We can access the current value of the input field using the inputRef.current.value property in the event handler function.
Difference between controlled and uncontrolled components in React?
Here is a comparison table highlighting the key differences between controlled and uncontrolled components in React:
| Aspect | Controlled Components | Uncontrolled Components |
| State Management | State is managed by React using useState or this.state. | State is managed by the DOM, and we access it using refs. |
| Value Control | The value of the form element is controlled by React state. | The value of the form element is controlled by the DOM. |
| Event Handling | Changes to the form element are handled through event handlers that update React state. | Changes to the form element are handled through event handlers that
access the value using refs like |
| Rerendering | The component re-renders on every change to the form element since the value is controlled by React state. | The component does not re-render on every change to the form element since the value is controlled by the DOM. |
What is Higher Order Component (HOC) in React?
A higher order component (HOC) is a function that takes a component and returns a new component with enhanced functionality. HOC can add additional props, state, or behavior to the wrapped component without modifying the original component’s code.
- HOCs are a pattern used in React to reuse component logic and can be used for tasks like authentication, data fetching, or theming.
- For example - We can create a higher order component that adds authentication functionality to a wrapped component:
function withAuthentication(WrappedComponent) { return function AuthenticatedComponent(props) { const isAuthenticated = // logic to check if user is authenticated if (isAuthenticated) { return <WrappedComponent {...props} />; } else { return <div>Please log in to access this content.</div>; } };}
// Usage:const ProtectedComponent = withAuthentication(MyComponent);In this example, the withAuthentication function is a higher order component that can take any component (like MyComponent) and return a new component (AuthenticatedComponent) that checks if the user is authenticated before displaying the wrapped component. If the user is not authenticated, it displays a message instead. This allows us to add authentication functionality to any component without modifying its original code.