Our ReactJs Interview Questions is the one-stop resource which helps you to boost your interview preparation. The main aim of our blog is to boost your confident level and make you crack the interview successfully. We have 100+ questions on ReactJs Programming basics prepared by our expert team that help you with different expertise levels to reap the maximum benefit from our blog. These most frequently asked questions are revised every three months to cope up with the industry standard.
React JS is a front end JavaScript library for developing complex and interactive web and mobile UI with reusable components by Facebook. It has huge ecosystem of libraries to choose the tools, libraries. architecture based on the requirements.
JASX stands for JavaScript XML.JSX is a syntax extension to JavaScript which is similar to XML/HTML like syntax used by React that helps to put HTML into JavaScript.
The virtual DOM is a programming concept where the virtual representation of a UI is kept in memory and synced with the real DOM by a library such as React DOM.
When creating a React component, it has to include the extends React.Component statement, that creates an inheritance to React.Component, and gives the component access to React.Component’s functions. The component also requires a render() method, this method returns HTML.
React Element is a simple object that describes a DOM node and its attributes or properties as per our requirement. It is an immutable description object and any method cannot be applied on it. React Component is a function or class that accepts an input and returns a React element
The React DOM. render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.
Strict Mode is a tool for highlighting potential problems in an application. It does not render any visible UI. It activates additional checks and warnings for its descendants.
The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behaviour of the component. It is mutable and accessed via this.state().
React can perform actions based on user events. An event is an action that could be triggered as a result of the user action or system generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes.
Pure Components are the components which do not re-render when the value of state and props has been updated with the same values. If the value of the previous state or props and the new state or props is the same, the component is not re-rendered.
The key difference between props and state is that state is internal which means owned locally and controlled, updated by the component itself while props are external, read only, owned by a parent component and controlled by whatever renders the component.
React Fiber is the new reconciliation algorithm which is an ongoing reimplementation of React’s core algorithm and uses stack internally. The goal is to increase its suitability for areas like animation, layout, and gestures with incremental rendering.
In a controlled component, form data is handled by a React component which allows validation control whereas in uncontrolled components, form data is handled by the DOM itself and use a ref to get form values from the DOM.
Reconciliation is the process through which React updates the DOM. React has to calculate if it is necessary to update the DOM when a component’s state changes. It does this by creating a virtual DOM and comparing it with the current DOM.
React shouldComponentUpdate is a performance optimization method that helps to avoid re-rendering a component, even if state or prop values may have changed which returns a boolean value.
A Key is a special string attribute needed to include when creating lists of elements in React. Keys helps to identify which items in the list are changed, updated, or deleted.
React Intl is an open-source project with library makes internalization in React straightforward, with off-the-shelf components and an API that can handle everything from formatting strings, dates, and numbers, to pluralization. It has a set of React components that provide a declarative way to setup an i18n context and format dates, numbers, and strings for display in a web UI.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. It catches errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
Lifecycle methods are called the component’s lifecycle methods and are invoked in a predictable order. It can be split in four phases: initialization, mounting, updating and unmounting.
Redux is a predictable state container designed to write JavaScript apps that behave consistently across client, server, and native environments and are easy to test.
where event.target.id is used as the state key to be updated.
React Portal is a most common use case which helps to render child components into a DOM node outside of the parent DOM hierarchy defined by the component tree hierarchy.
The primary difference of Flux vs Redux is that Flux includes multiple Stores per app, but Redux includes a single Store per app. Rather than placing state information in multiple Stores across the application, Redux keeps everything in one region of the application.
React Router is a standard library for routing that enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
29. What is the use of react DOM package?
The react-DOM package provides DOM-specific methods that can be used at the top level of the applications with methods like render(), hydrate().
30. Differentiate between react routing and conventional routing?
In conventional routing, each view corresponds to a new file with navigation with URL changes using Http request whereas in react routing, only single HTML page is involved with only changes in history attributes.
31.What are the limitations of React?
- React is not a full-blown framework
- Its library is very large and time taken to understand
- It can be little difficult to understand
- Coding gets complex as it uses inline templating and JS
32. Why can’t browsers read JSX?
Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. So to enable a browser to read JSX, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.
33. “In React, everything is a component.” Explain?
Components are the building blocks of a React application’s UI which can split up the entire UI into small independent
34. What are synthetic events in React?
Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event that combine the behaviour of different browsers into one API. This is done to make the events to show consistent properties across different browsers.
35. What do you understand by refs in React?
Refs is the short form for References in React which is an attribute which helps to store a reference to a particular React element or component that can be returned by the components render configuration function.
36. How are forms created in React?
React forms are similar to HTML forms but the state is contained in the state property of the component and is only updated via setState(). Thus the updation of the state is done using their submission by a JavaScript function.
37. What are Higher Order Components (HOC)?
Higher Order Component is an advanced way of reusing the component logic. These are custom components which wrap another component within it that can accept any dynamically provided child component.
38. What can you do with HOC?
- HOC can be used for many tasks like:
- Code reuse, logic and bootstrap abstraction
- Render high jacking
- State abstraction and manipulation
- Props manipulation
39. Explain Flux.
Flux is an architectural pattern which enforces the uni-directional data flow that controls derived data and enables communication between multiple components using a central Store.
40. List down the components of Redux.
Action – object that describes what happened.
Reducer – a place to determine how the state will change.
Store – State/ Object tree of the entire application is saved in the Store.
View – Simply displays the data provided by the Store
41. Explain the role of Reducer.
Reducers are pure functions which specify how the application’s state changes in response to an ACTION. It takes in the previous state and action and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values.
42. What is the significance of Store in Redux?
A store is a JavaScript object that holds the application’s state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store.
43. What are the advantages of Redux?
Advantages of Redux are listed below:
- Predictability of outcome
- Maintainability
- Server-side rendering
- Developer tools
44.What is prop drilling?
Prop Drilling is the process that helps to pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around.
45. What is Shallow Renderer in React testing?
Shallow rendering helps to render a component one level deep and assert facts about what its render method returns, without worrying about the behaviour of child components, which are not instantiated or rendered. It is useful for writing unit test cases in React.
46. What is the use of refs?
The ref is used to return a reference to the element. It can be useful when you need a direct access to the DOM element or an instance of a component. It can be created using React.createRef() method and attached to React elements via the ref attribute.
47.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. 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.
48. What is context?
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
const {Provider, Consumer} = React.createContext(defaultValue)
49.What is children prop?
Children is a prop (this.props.children) that allow passing components as data to other components, just like any other prop to use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.
50. What is ReactDOMServer?
The ReactDOMServer object enables to render components to static markup which is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:
- renderToString()
- renderToStaticMarkup()
51. How to use innerHTML in React?
The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. It is risky to use this attribute considering cross-site scripting (XSS) attacks, pass a __html object as key and HTML text as value.
52. What will happen if you use props in initial state?
If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component. The initialization of state from props only runs when the component is first created.
53. What are React Mixins?
Mixins are a way to totally separate components to have a common functionality. It should not be used and can be replaced with higher-order components or decorators. One of the most commonly used mixins is PureRenderMixin.
54. What are the Pointer Events supported in React?
Pointer Events provide a unified way of handling all input events. Many devices are used now a day that don’t correlate with a mouse, like phones with touch surface or pens. So we need to remember that these events will only work in browsers that support the Pointer Events specification.
55. What is the difference between setState() and replaceState() methods?
The current and previous states are merged when we use setState() . replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().
56. Why is a component constructor called only once?
React’s reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it’s the same component as before, so reuses the previous instance rather than creating a new one.
57. Is it possible to use async/await in plain React?
If you want to use async/await in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.
58. What are the popular packages for animation?
React Transition Group and React Motion are popular animation packages in React ecosystem.
59. What is the benefit of styles modules?
It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.
60. What are the popular React-specific linters?
ESLint is a popular JavaScript linter. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.
61. How React Router is different from history library?
React Router is a wrapper around the history library which handles interaction with the browser’s window.history with its browser and hash histories. It also provides memory history which is useful for environments that don’t have global history, such as mobile app development and unit testing with Node.
62. What is the purpose of push () and replace() methods of history?
Push (), replace() are the methods for navigation purpose in history instance. Push () will add a new location to the array and replace() will replace the current location in the array with the new one.
63. How to get query parameters in React Router v4?
The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementation. So the decision has been given to users to choose the implementation they like.
64. How to pass params to history.push method in React Router v4?
While navigating you can pass props to the history object using push method by specifying the path name and get the response through state. The search property is used to pass query params in push() method.
65. What are the two ways of formatting in React Intl?
The library provides two ways to format strings, numbers, and dates:
- Using react components
- Using an API
66.How to format date using React Intl?
The injectIntl() higher-order component will give access to the formatDate() method via the props in the component. It is used internally by instances of FormattedDate and it returns the string representation of the formatted date.
67. What is TestRenderer package in React?
This package provides a renderer that can be used to render components to pure JavaScript objects, without depending on the DOM or a native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.
68. What is Jest?
Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It’s often used for testing components.
69. Can I dispatch an action in reducer?
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
70. How to use FormattedMessage as placeholder using React Intl?
The Formatted… components from react-intl return elements, not plain text, so they can’t be used for placeholders, alt text, etc. In that case, you should use lower level API formatMessage(). You can inject the intl object into your component using injectIntl() higher-order component and then format the message using formatMessage() available on that object.
71.How to format date using React Intl?
The injectIntl() higher-order component will give you access to the formatDate() method via the props in your component. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date.
72. What is the purpose of ReactTestUtils package?
ReactTestUtils are provided in the with-addons package and allow to perform actions against a simulated DOM for the purpose of unit testing.
73.What is Jest?
Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It’s often used for testing components.
74. How to access Redux store outside a component?
To access Redux store export the store from the module where it created with createStore().
store = createStore(myReducer)
export default store
75. What are the drawbacks of MVW pattern?
DOM manipulation is very expensive which causes applications to behave slow and inefficient. Due to circular dependencies, a complicated model was created around models and views.
76. What does trend analysis means?
A trend analysis is an aspect of technical analysis that tries to predict the future
movement of a stock based on past data.
77. What is the proper way to access Redux store?
The best way to access Redux store in a component is to use the connect() function, that creates a new component that wraps around the existing one. This pattern is called Higher-Order Components, and is generally the preferred way of extending a component’s functionality in React.
78. What is the difference between component and container in React Redux?
Component is a class or function component that describes the presentational part of the application whereas container is an informal term for a component that is connected to a Redux store and subscribe to Redux state updates and dispatch actions.
79. What is redux-saga?
Redux-saga is a library that aims to make side effects that is asynchronous things like data fetching and impure things like accessing the browser cache in React/Redux applications easier and better.
80. What is the difference between React Native and React?
React is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications.
React Native is a mobile framework that compiles to native app components, for building native mobile applications in JavaScript that allows to use React to build your components, and implements React under the hood.
81. What is reselect?
Reselect is a selector library which uses memorization concept. It keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes. If the the same inputs are provided twice in a row, Reselect returns the cached output. It’s memoization and cache are fully customizable.
82. What are the advantages of React over Vue.js?
- Easier to test with more flexibility in large apps developing
- Suitable for mobile apps creating.
- More information and solutions available.
83. What are Styled Components?
Styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.
84. Can Redux only be used with React?
Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.
85. What is render hijacking in react?
The concept of render hijacking is the ability to control what a component will output from another component. It actually means decorating your component by wrapping it into a Higher-Order component. By wrapping you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enables hijacking, but by using HOC you make your component behave in different way.
86. What is React memo function?
Class components can be restricted from rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.
87. In which scenarios error boundaries do not catch errors?
The cases in which error boundaries doesn’t work are,
- Inside Event handlers
- Asynchronous code using setTimeout or requestAnimationFrame callbacks
- During Server side rendering
- When errors thrown in the error boundary code itself
88. What is the behavior of uncaught errors in react 16?
In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.
89. What is the required method to be defined for a class component?
The render() method is the only required method in a class component. i.e, All methods other than render method are optional for a class component.
90. What is React memo function?
No, it is not mandatory. i.e, If you initialize state, you can use a constructor for your React component.
91. What are the methods invoked during error handling?
Below methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
- static getDerivedStateFromError()
- componentDidCatch()
92. What is the browser support for react applications?
React supports all popular browsers, including Internet Explorer 9 and above, although some polyfills are required for older browsers such as IE 9 and IE 10. If you use es5-shim and es5-sham polyfill then it even support old browsers that doesn’t support ES5 methods.
93. What is code-splitting?
Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime. The react project supports code splitting via dynamic import() feature.
94. What is the benefit of strict mode?
- Identifying components with unsafe lifecycle methods.
- Warning about legacy string ref API usage.
- Detecting unexpected side effects.
- Detecting legacy context API.
95. What is NextJS and major features of it?
Next.js is a popular and lightweight framework for static and serverrendered applications built with React. It also provides styling and routing solutions. Below are the major features provided by NextJS.
- Server-rendered by default
- Automatic code splitting for faster page loads
- Simple client-side routing (page based)
96. What is React memo function?
If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways,
- Throttling
- Debouncing
- RequestAnimationFrame throttling
97. What are the conditions to safely use the index as a key?
There are three conditions to make sure, it is safe use the index as a key.
- The list and items are static– they are not computed and do not change
- The items in the list have no ids
- The list is never reordered or filter
98. What are the advantages of formik over redux form library?
- The form state is inherently short-term and local, so tracking it in Redux (or any kind of Flux library) is unnecessary.
- Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE. This way it increases input latency for large apps.
- Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB.
99. What is dynamic import?
The dynamic import() syntax is a ECMAScript proposal not currently part of the language standard. It is expected to be accepted in the near future. You can achieve code-splitting into your app using dynamic import.
If you want to do code-splitting in a server rendered app, it is recommend to use Loadable Components because React.lazy and Suspense is not yet available for server-side rendering. Loadable lets you render a dynamic import as a regular component.