Introduction to ReactJS – Why Use ReactJS?
React uses a virtual DOM (Document Object Model), which improves performance by reducing the amount of direct manipulation of the actual DOM. Additionally, React's component-based architecture makes it easy to reason about and maintain large codebases. As the second most loved framework according to Stackoverflow Developer Survey (2020), it is also widely supported and has a large developer community.
With the ReactJS library constantly changing, hiring managers and employers will naturally evaluate the skill level of their candidates during interviews. As a result, candidates will have to keep their skills and knowledge up to date in order to impress their interviewers, stand out from the
competition, and get hired for the job.
With the many ways interviewers can quiz candidates on ReactJS, HackerTrail has put together this comprehensive guide to help candidates best prepare for their interviews.
- What Are the Advantages and Disadvantages of ReactJS
- What do you understand by an event in React.JS and how to create it?
- What are the limitations of ReactJS
- How Would You Describe the Data Flow in ReactJS?
- Does React Guarantee that State Updates Will be Asynchronous?
- Can You Explain What Virtual DOM is in React JS?
- What are the Main Concepts of ReactJS?
- How Can You Embed Two or More Components into One Component?
- What are React Class-Based Components and Functional Components?
- What Is a Hook?
- What Is a Controlled Component and How Can You Create It in ReactJS?
- What is an Uncontrolled Component and How Can You Create It in ReactJS?
- What Are Refs and How Do You Use Them to Get DOM Values?
- What is a Higher-Order Component (HOC) and How Can a HOC Be Created to Share the Common Functionality Across Multiple Components?
- Why Use React Instead of Directly Manipulating the DOM?
- Which Language Implements the Virtual DOM and Why?
- Is it Important to Keep State Immutable in React Applications? Why or Why Not?
- What is Redux and What is its Significance?
- Why Are Props Better Than State?
- Explain the differences between real DOM and virtual DOM in React.JS.
- How can one prevent injection attacks in React?
- Explain the differences between stateful and stateless components in React.JS
- What is a state in React? How can we implement it?
- When would you use a Class Component over a Functional Component?
- Explain the differences between props and state in React.JS.
- Explain the differences between class and functional components in React.JS.
- What is HOC in React.JS?
- What are the methods which create a component lifecycle in React?
- Explain the ways to prevent a function from being called too quickly.
- What are the components of Redux in React.JS?
- What are the differences between Redux and Flux in React.JS?
- What are the advantages of Redux?
- Under what conditions would you consider using Redux with React?
React JS Basic Interview Questions
1. What are the advantages and disadvantages of React.JS?
Advantages of React.JS:
- Good learning curve: React.JS has a good online community and support is available for training and learning.
- Reusable: It is made of components which are combined with other components to provide reusability.
- SEO support: Provides SEO inclusion and hence supports businesses by better rankings.
- Better speed: Provides better speed through virtual DOM.
Disadvantages of React.JS
- Frequent changes: Technology is changing and upgrading at a fast pace, and therefore the programmer has to keep up with the learning process continuously.
- Documentation: There is no proper documentation available for React.JS due to frequent changes and upgrades in the technology. Therefore, the process of maintaining written documentation is a hassle.
- JSX increases complexity: Usage of JSX in React.JS increases the complexity and confusion for the new programmers. Therefore, they need to add this to their training schedule.
2. What do you understand by an event in React.JS and how to create it?
Event means reactions after a user action, e.g. mouse click, mouse hover, double click, keypress, etc. Handling events is similar to handling HTML DOM(Document Object Model) events. The difference is that in React.js we use JSX and pass the function as ‘event handler’. Also, we cannot pass ‘false’ as a return value to stop default behaviour, we specifically need to call ‘preventDefault()’. Find out more about React.JS events.
Commonly Asked ReactJS Interview Questions and Answers
Here are some of the most frequently asked ReactJS interview questions and answers of various levels of difficulty to help you ace your interview.
3. What are the Limitations of ReactJS?
While ReactJS offers many benefits to developers, there still exist some of the following limitations:
- Another disadvantage of using this library is its lacklustre support on mobile devices since all DOM interactions need to go through browser APIs instead of WebViews which means slower operations overall due only one round trip between server-side rendering cycle time and client-side execution time plus high bandwidth usage per request. This could lead up towards serious cost issues.
- To summarise the point above, React is a full client-side application, unlike other frameworks like PHP or Python. Everything happens on the front end (browser or client-side) from rendering the web page and data fetching. The disadvantages of client-side web applications are:
- Poor Search Engine Optimisation (SEO) – Website built on top of React tends to rank poorly, as search engine’s web crawler will not be able to crawl any content from the website because contents are not pre-rendered. Instead, the web crawler will be crawling an empty page.
- Poor User Experience (UX) on slower devices – Leaving rendering to the client-side can add seconds of load time on slower laptops and mobile devices. This can lead to users getting frustrated and leaving a website before it finishes loading.
- Slower loading time – A client-side rendered application needs to make an additional round-trip to the API server to render. This means the website will always load slower than an equivalent server-side rendered or static application.
However, the disadvantages of client-side React are only applicable to web applications that are built purely on the vanilla React library. These disadvantages are addressed with React frameworks like NextJS and Gatsby.
Source: Frontend Digest
4. How Would You Describe the Data Flow in ReactJS?
The data flow in ReactJS is a unidirectional one, meaning that when creating an app using React, the child components are nested within the parent components. With data flowing in one direction, it makes it easier for developers to find and debug errors in an application at any moment. This one-way databinding allows applications to be built in a modular and fast manner.
5. Does React Guarantee that State Updates Will be Asynchronous?
There is no guarantee that state updates are asynchronous, but React can be used with any other framework or architecture that updates the user interface with rendering, which is the case for most.
This does not apply to Redux and other similar Flux-like architectures in which dispatching actions control the flow of data instead. Typically, ReactJS offers more flexibility than most frameworks out there regarding data manipulation and state management.
6. Can You Explain What Virtual DOM is in React JS?
Rather than dealing directly with HTML tags, the VDOM’s JSON-like format only contains data on how things should appear to reduce the number of changes overall. This is what is known as reconciliation, or diffing, which is the process of measuring the differences between the old and new state of a component (i.e. seeing what changed in the old and new versions of an application). This lets React components re-render only the changed components of the app so that as little work as possible needs to be done with each update, therefore improving the performance of the app.
7. What are the Main Concepts of ReactJS?
The main concepts of ReactJS are components, props, state, events and lifecycle methods.
8. How Can You Embed Two or More Components into One Component?
Embedding two or more components into one component can be done using the React.createClass() and React.cloneElement().
This works in three steps:
- First, pass down a function as a prop to one of the components you have. When you need to render that component inside another one, this function will be called.
- Next, use the cloneNode() method on the root node of the source component, then pass its children as new children nodes on the destination element.
- Last, as cloneNode() does not copy event handlers from its source element, you must use .setState() to manually register them again with your cloned elements.
9. What are React Class-Based Components and Functional Components?
10. What Is a Hook?
React Hooks are a new feature in React 16.8 which enable you to add state and lifecycle methods to functional components. Before hooks were a feature, only class-based components had access to state and life cycle methods.
Hooks allow you to write more powerful, expressive, and easier to understand functional components and are widely considered to be a preferred way of writing React components. This is because they are more lightweight and easier to understand compared to class-based components.
11. What Is a Controlled Component and How Can You Create It in ReactJS?
A controlled component are components whose value is directed/driven by React’s state. Its state is mutated by calling setState method or useState hook. Here are explanations for the class based React component and the React functional component.
Class Based React Component
In a class based React component, a controlled component can be extending the React.Component class and defining an instance property called _state. A _state property has to be declared as an object with key/value pairs for each property or data piece in a component’s state.
In order to mutate the states, the setState method is used to update the component's state. The setState method is a built-in method provided by React that allows you to update the state of a component and re-render the component with the updated state.
React Functional Component
For a functional component, a controlled component utilises the “useState” React hook to track and mutate states in the component.
12. What is an Uncontrolled Component and How Can You Create It in ReactJS?
An uncontrolled component is a React component that manages its own state internally and has its state set by the parent component. Creating an uncontrolled component in ReactJS requires the use of a stateless functional component syntax.
13. What Are Refs and How Do You Use Them to Get DOM Values?
The ref attribute is used to obtain DOM values. The ref attribute can be used to access the DOM, and refs themselves are accessed using this.refs, which is an empty object unless a reference has been set otherwise.
Refs are handy when it comes to accessing an input field or text area in a React component and you want it updated whenever a user makes changes to something that affects its value. However, it is not feasible or possible to pass props down through all component levels as required, for instance, if a component requires a reference to a button.
Class Based React Component
Here is an example for a class based React component:
Using React.createRef(), Refs are created and then attached to React elements through the ref attribute. Usually, they are assigned to an instance property when a component is constructed. This allows for them to be referenced throughout the component.
React Functional Component
For functional component, Refs can be created using React’s useRef hook. useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). For the full lifetime of the component, the returned object will remain.
14. What is a Higher-Order Component (HOC) and How Can a HOC Be Created to Share the Common Functionality Across Multiple Components?
A Higher-Order Component (HOC) is a function that takes a component and returns another component. HOC is used to add additional behaviour to an existing component.
Here is an example to illustrate this. If we want some common functionality for two components, it will look like this:
- The first one has the background colour red and displays its name as "MyComponent1"
- The second one has the background colour blue and displays its name as "MyComponent2"
15. Why Use React Instead of Directly Manipulating the DOM?
Manipulating the DOM directly is not a good practice as it can result in performance issues as well as difficulty in debugging. This is because it is hard to understand what has happened in an application (unless there is a visual depiction of how specific elements were added and removed from the DOM).
With ReactJS, you’re able to create reusable components using HTML attributes, a concept that is found in jQuery. This is when a component has properties, similar to an attribute, that outline its behaviour regarding what it does for its parent element or other components.
By enabling reuse across different applications or projects, this allows you to save your time and energy as you end up writing less code. This makes maintaining and debugging easier since the codebase does not require as much updating when there are changes because you are merely updating only what requires changing.
16. Which Language Implements the Virtual DOM and Why?
As V8 lacks access to external resources such as databases or file systems, unlike other programming languages which do have access to these, it does not have a persistent way to store data. As a result, it heavily relies on using references between objects (arrays) or objects instead. Everything within these references becomes part of a “Heap”, which is a big data structure that represents all objects currently existing within memory space allocated by V8 during startup time.
17. Is it Important to Keep State Immutable in React Applications? Why or Why Not?
It is crucial to keep the state immutable in React applications because this can prevent negative consequences from occurring. For instance, if a component’s state is mutable and a function is called on it, such as this.setState, the function can change the component’s state directly, meaning that others with access to your component are unable to tell whether its state has been changed.
However, this problem is easily avoided by keeping your data in an immutable form. Some key things to note are to not change any object property directly, but instead, make a new object and return that from setState(). You can also use another library such as Redux as it can provide you with a reducer API for doing that too.
18. What is Redux and What is its Significance?
Redux’s main feature is that it lets you track state changes in applications through actions and reducers. An action outlines what has changed or occurred in an application, while a reducer updates the store with new information when an action takes place.
19. Why Are Props Better Than State?
Props are passed down from parent to child and are immutable, more readable, and easier to debug and test.
Props can be considered better than state in the following ways:
- Props are explicit: As props are passed down from a parent component, it is clear where the data is coming from and how it is being used. As such, it is easier to understand and reason about a component’s behaviour.
- Props promote reusability: As props are passed down to a component, the component can be reused in different contexts with different data, making it easy to reuse and share components across an application.
- Props are more predictable: Props cannot be altered or changed by the component that receives them because they are immutable, which makes it easier to predict the behaviour of a component, and makes it easier to test.
- Props are easier to manage: Props are passed down to a component which does not need to manage the state itself, making it easier for handling the state and behaviour of a huge number of components.
DOMs and APIs
20. Explain the differences between real DOM and virtual DOM
DOM means Document Object Model in HTML, the elements in HTML are represented as nodes of the DOM. HTML is a text written inside tags, and DOM is a structural representation of those components.
A virtual DOM is a lightweight copy of the real DOM, which can be considered as a tree consisting of nodes. These nodes contain information about elements and their attributes.
Whenever there is a change in the virtual DOM due to a user action React updates the particular node. Then it compares this changed virtual DOM to the previous virtual DOM before the update and gets to know which nodes have to be updated. Now, finally, React will update only those nodes in the real DOM which were updated in virtual DOM. And these changes in real DOM affect the rendering on the screen.
21. How can one prevent injection attacks in React?
JSX used in the react framework prevents injection attacks. By default, react DOM escapes any values embedded in JSX. This helps in ensuring that we cannot inject anything which is not explicitly written in code. Because everything which is being rendered on the screen is first converted to a string. Due to this feature, XSS (cross-site scripting) is prevented by JSX in React.JS.
Components in React JS
22. Explain the differences between stateful and stateless components in React.JS
|Stateful components||Stateless components|
|They have a state, which gets initialised in the constructor.||They do not have any state.|
|Renders both props and states.||Renders props only.|
|Has information about the state change of the component.||Calculates the internal state of the component.|
|They have the authority to change the state of the component.||They don't have the authority to change the state of the component.|
23. What is a state in React? How can we implement it?
A state is an object in React.JS which determines the component behaviour and their rendering. It is a data source containing information about the react component. These are the properties of the component that control the behaviour of the object.
The state of the component can be accessed using this.state() and can be updated using this.setState().
24. When would you use a Class Component over a Functional Component?
If the component which we are using has states(react lifecycle), then we should use Class components otherwise we should use react functional components. Class components are also called Stateful components because they implement state and logic.
An example of a lifecycle method is componentDidUpdate() method.
25. Explain the differences between props and state in React.JS
|They are immutable, i.e. cannot be changed.||They are mutable or changeable.|
|Can be accessed by child components.||Cannot be accessed by child components.|
|Stateless components can have props.||Stateless components cannot have a state.|
|Props make components reusable.||A state in React cannot make components reusable.|
|They are external to components.||They are internal to components.|
|They are used to pass data.||They are used to manage data.|
26. Explain the differences between class and functional components in React.JS.
|Functional component||Class component|
|Known as Stateless components.||Known as Stateful components.|
|They do not implement any logic.||They implement logic before rendering.|
|Cannot use React lifecycle methods.||Uses React lifecycle methods.|
27. What is HOC in React.JS?
Higher Order Components(HOC) is a function that accepts a Component as an argument and returns a Component.
E.g. you can write a HOC to transform its input to lowercase. HOC is especially useful in the scenarios where we find ourselves writing a lot of code in different places that do the same thing, which you can refactor the code into a reusable HOC. It is an advanced technique to enhance reusability in React.JS.
These HOC receive data and return data based on the input data, and to update the HOC we need to change the input data. Interestingly, HOC transforms one component into another component by wrapping it into a container component.
Read more about High Order Components here.
28. What are the methods which create a component lifecycle in React?
The popular component lifecycle methods in React are:
- componentDidMount: It is executed after the first render. It is used to trigger the other lifecycle methods.
- shouldComponentUpdate: It returns true or false value to determine if a component will be updated or not.
- componentDidUpdate: It is called after rendering.
- componentWillUnmount: It is called after the component is unmounted.
29. Explain the ways to prevent a function from being called too quickly
During using event handlers like onClick or onScroll, there could be frequent and too fast calls which we would want to prevent. Below are the ways to prevent it:
- Throttling: Prevents calling of a function repeatedly in a specified time.
- Debouncing: Introduces a delay between two executions of a function.
- requestAnimationFrame throttling: It is a technique where a function to be executed is queued for optimising the rendering of the function.
Refer to the examples with code snippets here.
30. What are the components of Redux in React.JS?
Redux has below components:
- Actions: They are events like user interactions and API calls etc. which help sending data from an application to the Redux store. The actions are sent using store.dispatch() method.
- Reducers: They are pure functions which take a current state of a function as input, perform some action on it and then return the new state. All logic resides in the reducers.
- Store: It stores the application status, and it is recommended that only one store should be used per application. Stores the entire state tree of the application.
- Middleware: They are the interceptors of the action which are sent from components before passing them to the reducer function.
- View: It displays the data sent by the store by combining dumb and intelligent components.
31. What are the differences between Redux and Flux in React.JS?
|Includes multiple stores.||Has only one store.|
|The store handles all the logic.||Reducer handles all the logic.|
|The dispatcher helps in debugging.||A dispatcher is not present, due to single-store, debugging is easy.|
|It has a mutable/ changing state.||It has an immutable state.|
32. What are the advantages of Redux?
- Manageable: State of applications is easily manageable due to centralised global access.
- Debugging: It is easier to debug due to single store and complete error reports are sent to the server.
- Flexible: Provides add-ons to be used in the UI layers, which makes the development easier and flexible.
- Reusable: Promotes reusability due to global accessibility, same code can be tested on the client, server, and native environments.
- Maintenance: Redux has strict guidelines regarding the code structure, hence it becomes easy to maintain.
- Community support: Redux has great community support to help the developers when any issues are faced by them.
33. Under what conditions would you consider using Redux with React?
React Redux is recommended during the below scenarios:
- When the application states are changed frequently using complex logic.
- The application has a large codebase with many people working on it simultaneously.
- When monitoring of the application states is needed.
- When the application has a large number of application states used by different components.
34. What are the advantages of Router in React.JS
- Helps in dynamic route matching.
- Provides a browsing history feature to restore the state of the view.
- It provides a standard application structure for ease of understanding by team members.
- Eases the handling of nested views.
- It has slow code loading.
35. Why do we need a Router in React.JS
We need a router to navigate through the views of different components in a React application. It helps in displaying different views on a single-page application. It is a standard library/API which is used for dynamic routing in React.JS. It uses a component structure to call the components.
Using the react router, we can go forth and back, refresh the page and still maintain the view of the page without white flashes.
Final Essential Tips to Crack Your ReactJS Interview
There are countless questions an interviewer might ask you about ReactJS – the possibilities are endless – but this interview guide will adequately prepare you for the more commonly asked questions.
Ultimately, practice makes perfect when it comes to interviews, and doing well in one requires a combination of both technical knowledge as well as people skills in order to make the best impression on your interviewer. As this list is not exhaustive, do share your interview tips as well as other frequently asked ReactJS interview questions in the comments below!
Other Backend Technology Interview Questions and Answers
C Programming Language Interview Questions | PHP Interview Questions | .NET Core Interview Questions | NumPy Interview Questions | API Interview Questions | FastAPI Python Web Framework | Java Exception Handling Interview Questions | OOPs Interview Questions and Answers | Java Collections Interview Questions | System Design Interview Questions | Data Structure Concepts | Node.js Interview Questions | Django Interview Questions | Microservices Interview Questions | Key Backend Development Skills | Data Science Interview Questions | Python Interview Questions | Java Spring Framework Interview Questions | Spring Boot Interview Questions.