React Interview Questions and Answers

What is React?

React is a open source front end javascript library. It is used to develope user interfaces specially single page applications. React is extremely popular, declarative, component based, state driven javascript library created by facebook.

  • It supports client side as well as server side rendering
  • It uses Virtual DOM Rather than Real DOM as manipulation in Real DOM is very expensive
  • It uses reusable UI components for developing the view
  • It follows unidirectional data binding

What do you like about react and what you don't?

I like the unidirectional flow from parent to child. I like react because it is almost like javascript

Angular and vue has there own syntax, they are two way data flow

The jsx in React is very much html. Developers with primary skills html and css, can work easily with JSX

What is virtual dom in react?

For any data changes, the entire UI is rendered in virtual DOM representation, then the difference between the previous DOM(real DOM) and the virtual DOM is calculated, it identifies only the changes and only that changes are updated instead of rendering the complete DOM it only updates the changes in the real DOM

What is Virtual dom and Real DOM

Real DOM

  1. When ever element updates, it creates new DOM
  2. There is too much of memory wastage here
  3. It is slow
  4. Manipulation of DOM is very expensive

Virtual DOM

  1. Updates the JSX if element is updated
  2. Here there is no memory wastage
  3. It is very fast
  4. Manipulation of DOM is easy

What are the limitations of React

React is just a javascript library, not a framework

What are the benefits of using React

  1. React increases application performance. It uses the Virtual DOM to render the view, virtual DOM which consumes less memory and DOM manipulation is quite easy, so it increases the application performance. Virtual DOM is a virtual representation of the DOM, each time when the data changes, a new virtual DOM gets created. Creating the virtual DOM is much easier than rendering the UI in the browser. With the use of Virtual DOM the efficiency of the application enhances.
  2. React can be used on client side as well as server side
  3. Anyone who has the basic knowledge of javascript can start building applications with React
  4. React uses component based architecture for developing applications. components are independent and reusable. components can be shared across various applications having same functionality. Components describe a part of the user interface. There are two types of components , stateful class components and stateless functional components.
  5. React can be used with other frameworks like Angular , Vue etc
  6. Using React, in less time we can write test cases
  7. React is SEO friendly, it allows to develop great user interfaces that can be easily navigated in search engines, the server side rendering of React allows us to enhance SEO of the application
  8. React provides us with number of tools and libraries and architecture for developing an application based on our requirements

How does the browser reads the JSX

Browsers can not read the JSX code, as it is not a javascript object

For the browsers to read the JSX we have to use compiler to transform jsx into javascript object using compiler like Babel

What is a State in React

The state is a built-in React object which is used to store data in a component. A component's state can change over time whenever it changes, the component re-renders

When ever the data in components state changes, the component is re-rendered. State can influence what is rendered in the browser, state can be changed within the component

What are props?

Props are properties which are optional inputs which are passed as parameters in React components. Props allows the component to be dynamic.

Props are passed to components through html attributes from one component to other component

What are props and states

Both props and state hold information which influences the ui in the browser

Props

  1. Props are read only
  2. Props are immutable because they are passed down to the child components. Props are passed as function parameters
  3. Props gets passed to the component
  4. Props can be accessed by the child components
  5. Props are used to communicate between components
  6. Stateless functional components can have props
  7. Props can make components reusable
  8. Props allow you to pass data from one component to other component as an argument
  9. in functional components props can be accessed using props
  10. in class components props can be accessed using this.props

States

  1. State changes can be asynchronous
  2. State is mutable , declared as variables in the function body
  3. State can not be accessed by the child components, state is managed within the component
  4. State can be used for rendering dynamic changes with the component
  5. Stateless class components cannot have state
  6. State cannot make components reusable
  7. State contains information about the components
  8. state can be accessed using useState hook in functional components
  9. In class components state can be accessed using this.state

What are life cycle phases in React

There are three different phases of lifecycle of React components

  1. Initial Rendering Phase: This is the phase when the component is about to start its journey and added to the DOM
  2. Updating Phase: Once the component is added to the DOM, it can update and re-render only when a prop or a state change occurs.
  3. Un mounting Phase: This is the final phase of the component life cycle in which the component is destroyed and removed from the DOM

What is the key in react?

Keys helps react identify which items have changed or added or removed. Key is a string attribute needs to be included mostly when we are working on list items. Key prop is not accessible in the child component

Keys should be used on array elements to provide an unique identity for each element

React do not understand the order of the list item if we do not provide it with the key

only with the key, React understands which particular item is edited, deleted, added or updated

Render the list items with map, do not use loops. Give each item a unique key, do not use array index as the key value

When can you use index as key?

  • When the items in your list do not have a unique id
  • When the list is static and you know it will not change
  • When you know the list will never be reordered or filtered

What is strict mode in React

It is a helper function provided by React which allows us to write better code by activating additional checks and warnings for its descendants

What is higher order components in React(HOC)?

It is the advanced method of reusing the component functionality logic, it is easy to handle, makes code more readable, clean, efficient and more modular.

It takes another component as input and returns a wrapped version of itself

How you can call a api in react component

There are multiple ways of calling the Api in React.

You can use browser Api fetch to call Api, using external library Axios you can call it

Explain react hooks

React hooks are used in the functional components, as functional components are stateless components and also we don't have lifecycle methods. React has introduced hooks to maintain the state in the functional component.

Hook is a special function that lets you to hook into special features, hooks allows you to add react state to functional components

Types of Hooks

  • useState
  • useEffect
  • useReducer
  • useMemo
  • useContext
  • useRef
  • useCallback
  • useTransition
  • we can also have our custom hooks

What are react rules of using hooks?

  • Only call hooks at the top level
  • Don't call hooks inside the loops, conditions or nested functions
  • Only call hooks in the react functional components, not in the regular javascript functions
  • Hooks can be used in custom hooks

What is the use of Fragment in React

It is a feature of React which returns multiple elements

Fragment allow us to wrap all our list of elements without adding extra nodes to the DOM

What is useState() in React?

The useState() is a React hook which is used in functional components, it allows you to have state variables and have state in functional components. It should be used when the DOM has something that is dynamically manipulating. In class component the state is always an object. In functional components the state does not need to be an object. It can be any data value. useState hook returns an array with two elements. The first one is a current value of the state and the second one is a state setter function. New state value depends on the previous state value, you can pass a function to the setter function.

What is key difference between useState() and setState() in React?

The setState() will merge the values automatically where as in useState setter function, you have to manually merge the values. For example, when updating the value of a property in a object, you have to spread the old state and then update the properties of that state, this will preserve all state values

What is Children prop?

The Children prop allow us to pass JSX into an element.

What is lifting the state in React?

Whenever multiple sibling components need access to the same state, we move that piece of state up to the first common parent component

What is derived state?

State that is computed from an existing piece of state or props

what is useEffect() hook?

The useEffect hook lets you perform side effects in functional components

It is the replacement for componentDidMount, componentDidUpdate, componentWillUnmount

useEffect is used for handling side effects in the functional components

Why is class, className in react?

Class is a reserved keyword in javascript, our jsx gets compiled into javascript, there would be a conflict if we use class for css styling, javascript thinks that you trying to create javascript class, so for that reason class is className in jsx.

Should you use ternaries or && operator to conditionally render React components?

Ternaries are the best comparing to and operator, the reason is sometimes you get into specific problem like your left side of expression evaluates to zero which is false then it doesn't bother about right side of expression and returns false.

How would you delay an api call until a component is mounted?

In a class component we can use lifecycle method componentDidMount. In functional component we can use useEffect hook which will run after the component is rendered and should pass the second argument an empty dependency array which means it will only run once.

Describe data flow in react

The data flow in React is unidirectional. All the components in react have parent child relationship that we are passing down the data from parent to child in one direction, so all the data is going in one direction through the props. we share the data multiple layers deeper by passing the props downs which is called prop drilling.

What is JSX?

JSX stands for javascript XML. It allows to write html inside the javascript and place into the DOM without writing the javascript functions like createElement, appendChild etc.

JSX provides syntactic sugar for React.createElement() function.

We can create react applications without using JSX as well

What are the differences between functional and class components?

Class components are stateful components where as Functional components are stateless components, after the introduction of hooks in react, functional components are also stateful components with the usage of hooks.

Functional components

  1. Functional components are javascript functions and can be declared by using arrow function or function keyword
  2. Any prop provided as an argument to a functional component can be directly used inside HTML elements

Class components

  1. Class components are declared using ES6 class keyword
  2. In the case of class components, this keyword is used.

What are the differences between controlled and uncontrolled components?

Controlled and uncontrolled components are the different approaches to handling form input elements in react

In uncontrolled components you can only retrieve the value once on submit, validate the from on submit

In controlled components you can do field level validations, conditionally disabling submit buttons, enforcing input format and dynamic inputs

In a controlled component, the value of the input element is controlled by React. The state of the input is stored inside the code, and by event callbacks, any changes made to the input element will be reflected in the code as well

When a user enters data inside the input of a controlled component, onChange function is triggered and inside the code we check whether the entered value is valid or not. If it is valid then we change the state and re-render the input element with the new value

In an uncontrolled component, the value of the input element is handled by the DOM itself. Input elements inside uncontrolled components work like normal HTML input form elements. The state of the input element is handled by the DOM. Whenever the value of the input element is changed, event based callbacks are not called. React does not perform any action when there are changes made to the input element. Whenever user enters data inside the input field, the updated data is shown directly. To access the value of the input element, we can use ref

What are error boundaries?

Error boundaries are React components that catch javascript errors in their child component tree, log those errors and display a fall back UI.

A class component becomes error boundary by defining either or both of getDerivedStateFromError and componentDitCatch lifecycle methods

The placement of the error boundary also matters as it controls if the entire application should have the fall back UI or the component causing the problem

How does React use the Virtual DOM to render UI?

Virtual DOM is a concept where a virtual representation of the DOM is kept inside the memory and is synced with the Real DOM by a library called ReactDOM.

Every application deals with the DOM Manipulation, but the DOM manipulation is very slow when compared to other operations in javascript. The performance of the application is affected when several DOM manipulations are done. For every DOM change entire DOM is updated.

For a small change in the list item, instead of that item has to update, entire list is rendered again and the DOM is updated, which affects the performance of our application

To address this kind of inefficient updating, the react team came up and introduced the concept of virtual DOM

For every DOM object, there is a virtual DOM object, which is a copy of Real DOM. The difference between the Real DOM and the Virtual DOM is, any changes in the Virtual DOM will not directly reflect on the screen.

Consider a virtual DOM object as a blueprint of the real DOM object, whenever a JSX element gets rendered, every virtual DOM object gets updated

updating the virtual DOM is much faster then updating the real DOM since we are just updating the copy of the Real DOM

React uses two virtual DOM's to render the user interface. One of them used to store the current state of the objects and the other is used to store the previous state of the objects. Whenever the virtual DOM is updated, react compares the two virtual DOM's and get to know about which virtual DOM objects were updated, react updates on those objects inside the real DOM instead of rendering the complete real DOM.

What is memoize in react

Memoize in react is responsible for cache storing and improving performance

What is useRef

It is used to target the DOM elements directly, it preserves the value, it creates a mutable variable which does not trigger re-renders

What is custom hook?

A custom hook is a javascript function whose name starts with use. A custom hook can also call other hooks if required.

custom hook allows us to reuse the functionality

custom hook is like alternative to HOC and render props. Easy to share logic using custom hook instead of duplicate code in components

What are higher order components?

It is a pattern where a function takes a component as an argument and returns a new component.

What are render props?

The term render prop refers to a technique for sharing code between React components using a prop whose value is a function

What is the difference between react memo and useMemo

useMemo is a react hook, we can return memoized values and avoid re-rendering if the dependencies to a function have not changed


React.memo allows us to make a component only render if it's prop that it's accepting or in fact changing just because the parent component is changing but if the incoming props have not changed I don't want to render again

What is useContext in React?

context provides a way to pass data through the component tree without having to pass props down manually at every level

or

React context api allows you to easily access data at different levels of the component tree, without passing props to every level

What is the disadvantage of using context api

The way the react context API works is such that whenever something changes in your context it has no way of cleverly figuring out which component that uses this context really is concerned and which component is not. Which means that every component that uses use context will rebuild, will re-render when you switch something in that context. No matter if it's directly effected or not. And in general the react context API is simply not optimized and not meant to be your Global State Management tool in your app. It's meant for some states, like authentication status, like the theme but not for all your states because of these missing optimizations and all of this missing intent behind the context API. So, its not better option to use context API in larger projects.

What is useReducer?

useReducer is a hook that is used for state management. It is an alternative to useState.

useState vs useReducer

  • useStateuseReducer
  • Number of stateone or twotoo many
  • Related state transitions?noyes
  • business logicno business logiccomplex business logic
  • local vs globallocal stateglobal state
  • type of statenumber, string, booleanObject, array

What is useCallback

It is used to optimize performance.

useCallback is a hook that will return a memoized version of the callback function that only changes if one of the dependencies has changed

It is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

use cases of useCallback are when you are fetching the data, every time the component renders the fetch function runs. to memoize this we can use callback and pass the fetch function as a dependency in the array

when using remove item from a list when parent component renders the list also renders, to memoize the remove item function we can use useCallback when the list is not changing

What is difference between useCallback and useMemo

useCallback caches the provided function instance itself where as useMemo invokes the provided function and caches its results.

If you want to cache a function then use useCallback and if you want to cache the results then use useMemo

useMemo returns a memoized value

useCallback returns a memoized function

memoization is an optimization feature in React which, when used in the right place, increases the performance of the application

What is Suspense Api

Improve performance by splitting up a code into smaller, more manageable chunks. We can reduce the size of the initial JavaScript payload that needs to be loaded. This results in faster load times. And improved performance, especially on slow networks or low end devices. Second, better user experience with code splitting, only the essential code needed for the initial render of your application is loaded. The remaining code is loaded as the user interact with your application leading to a smoother, less blocking user experience.

What is difference between useLayoutEffect and useEffect?

useLayoutEffect run synchronously after a render but before the screen is updated

useEffect run asynchronously after a render is paint to the screen

Redux

What is Redux?

Redux is a state management library. Redux is a predictable state container for javascript apps.

Redux stores the state of your application

  • Holds application state
  • Allows access to state via getState()
  • Allows state to be updated via dispatch() function
  • Registers listeners via subscribe
  • Handles un registering of listeners via the function returned by subscribe

What is React-Redux library?

It is an official Redux UI binding library for React. It helps you to connect your react application to redux store

What are main concepts of Redux?

Redux is a store that holds the state of your application

An action that describes the changes in the state of the application

A reducer, which will actually carries out the state transition depending on action

What is middleware in redux

Middleware allows us to extend redux with custom functionality

Middleware provides third-party extension between dispatching an action and the moment it reaches the reducer

Using middleware we can log messages,crash reporting , performing asynchronous tasks etc.

What is useTransition() hook in React 18?

It is a hook that allows you to update the state without blocking the UI. It allows us to mark certain functionality less urgent which can prevent whole ui blocking.

Styling react components

  • CSS stylesheets
  • Inline css with style object
  • Using CSS modules
  • Using styled components and add the css in js

What are styled components?

Styled components is a css library. we can write css in js in our components. Can apply javascript logic in component css in js. Avoids name collisions. you can write nested css in styles. The styled component wrapper creates a unique class element per page avoiding name collisions.

you can create separate wrapper components and call in respective components, these are only responsible for styling.