
25+Top React JS Interview Questions & Answers [UPDATED]
Last updated on 15th Jun 2020, Blog, Interview Questions
Reactjs is an open-source javascript UI(User Interface) library, collaborated and maintained by Facebook and Instagram and also a huge community of developers. That’s designed to take your application state and allow you to write code that makes that status input and return virtual DOM, It’s a certainly better way to manipulate the DOM and handle events which are really just a set of the plain.
Here are a few React.js interview questions that answer about all the major elements of React Js. In this post, we have added some Basic and Advanced React Js Interview Questions. Thus, these questions are compiled with both basic and advanced level questions on React Js. Preparing for your interview with these questions, will give you an edge over the others and will help you crack the exam.
1. What is ReactJS ?
Ans:
React js is a java script based UI Library developed at Facebook, to create interactive, stateful & reusable UI components. It is one of the most popular java script frameworks that is created for handling the presentation layer for the web and mobile apps.
2. List some advantages of ReactJS ?
Ans:
Advantages of ReactJs:
- React.js is extremely efficient: React.js creates its own virtual DOM where your components actually live. This approach gives you enormous flexibility and amazing gain in performance. React.js also calculates what are the changes needed to be made in DOM. This process of React.js avoids expensive DOM operations and makes updates in a very client manner.
- It makes writing Javascript easier: React.js uses a special syntax called JSX, which allows you to mix HTML with Javascript. The user can drop a bit of HTML in the render function without having to concatenate strings, this is another fantastic thing. React.js turns those bits of HTML into functions with a special JSXTransformer.
- It gives you out-of-the-box developer tools: When you start your journey with React.js, do not forget to install the official React.js chrome extension. It makes debugging your application much easier. After you install the extension, you will have a direct look into the virtual DOM as if you were browsing a regular DOM tree in the elements panel. Isn’t it pretty amazing!
- It’s awesome for SEO: One of the biggest problems with other Javascript frameworks is that they do not search engine friendly. Though there have been some improvements in this area, search engines generally have trouble reading Javascript heavy applications. React.js stands out from the crowd because you can run React.js on the server, and the virtual DOM will be rendered to the browser as a regular web page.
- UI Test Cases: It is extremely easy to write UI test cases because the virtual DOM system is implemented entirely in JS.
3. What are Components in ReactJS ?
Ans:
React Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
Below is an ample component written in ES6 class to display a welcome message on the screen:
- class Welcome extends React.Component {
- render() {
- return <h1>Hello, {this.props.name} </h1>;
- }
- }
- const element = <Welcome name=”Sara” />;
- ReactDOM.render(
- element,
- document.getElementById(‘root’)
- );
4. List some features of ReactJS ?
Ans:
Undoubtedly today React is among one the best JavaScript UI frameworks. It comes with a lot of features that help programmers to create beautiful applications easily, we have listed some of them below.
- It’s Adaptability
- Free and Open Source
- Decorators from ES7
- Server-side Communication
- Asynchronous Functions & Generators
- Flux Library
- Destructuring Assignments
- Usefulness of JSX
5. What are refs in ReactJs ?
Ans:
React ref is used to store the reference of element or component returned by the component render() configuration function.Refs should be avoided in most cases, however, they can be useful when we need DOM measurements or to add methods to the components.
Refs can be used in the following cases:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
6. Explain the life Cycle of React JS Component ?
Ans:
React JS Component Lifecycle:
Each component has several “lifecycle methods” that you can override to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens.
Mounting
These methods are called when an instance of a component is being created and inserted into the DOM:
- constructor()
- componentWillMount()
- render()
- componentDidMount()
Updating
An update can be caused by changes to props or state. These methods are called when a component is being
rendered
- componentWillReceiveProps()
- shouldComponentUpdate()
- componentWillUpdate()
- render()
- componentDidUpdate()
Unmounting
This method is called when a component is being removed from the DOM:
- componentWillUnmount()
Other APIs
Each component also provides some other APIs:
- setState()
- forceUpdate()
Class Properties
- defaultProps
- displayName
Instance Properties
- props
- state
7. What is flux in JavaScript?
Ans:
Flux is an application architecture for creating data layers in JavaScript applications.It was designed at Facebook along with the React view library.Flux is not a framework or a library. It is simply a new kind of architecture that complements React and the concept of Unidirectional Data Flow.
8. What is the difference between Dom and virtual Dom in ReactJS ?
Ans:
DOM is the acronym for Document Object Model. Dom is also called HTML DOM as it is an abstraction of structured code called HTML for web developers. Dom and HTML code are interrelated as the elements of HTML are known as nodes of DOM. It defines a structure where users can create, alter, modify documents and the content present in it. So while HTML is a text, DOM is an in-memory representation of this text.
Virtual DOM is an abstraction of abstraction as it has been derived from HTML DOM. It is a representation of DOM objects like a lightweight copy. The virtual DOM was not invented by React, it is only used and provided for free.
9. What are portals in React?
Ans:
Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
ReactDOM.createPortal(child, container)
The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.
10. What are the controlled components and uncontrolled components in ReactJS ?
Ans:
Controlled components are more advisable to use as it is easier to implement forms in it. In this, form data are handled by React components. A controlled input accepts values as props and callbacks to change that value.
The uncontrolled component is a substitute for controlled components. Here form data is handled by DOM itself. In uncomfortable components, the ref can be used to get the form values from DOM.
11. Explain the difference between functional and class components.
Ans:
Functional components are those components that return React elements as a result. These are just simple old JavaScript functions. React 0.14 has given a new shortcut for creating simple stateless components that are known as functional components. These components make use of easy JavaScript functions.
Class components: Most of the tech-savvy people are more familiar with class components as they have been around the corner for a longer time. These components make use of plain old javascript objects for creating pages, mixins, etc in an identical way. Using React to create a class factory method, a literal is passed in defining the methods of a new component.
12. What do you understand by mixing or higher order components in ReactJs ?
Ans:
Higher order components (HOC) is a function that takes a component as well as returns a component. It is a modern technique in React that reuses the component logic. However, Higher order components are not a part of React API, per se. These are patterns that emerge from React’s compositional nature. In other words, HOC’s are functions that loop over and apply a function to every element in an array.
13. How is flux different from redux?
Ans:
Difference Between FLUX and Redux
FLUX | REDUX |
---|---|
Flux is a container for application state and logic that are registered to callbacks. | Redux is a container for JavaScript apps. |
It is an observer pattern that is modified to fit React. | It offers interesting features such as writing applications, testing in different environments such as a server, client, etc. |
It is a fancy name given to observer patterns and Facebook has developed tools to aid the implementation of these patterns. | In redux, actions can be functions or promises. |
Flux supports actions that are simple JavaScript objects. | Redux is the first choice for web developers because it offers live code editing. |
14. How is ReactJS different from angular and VUE js?
Ans:
AngularJs: Developed by Google, angular is a typescript based JavaScript application framework. It is also known as Superheroic JavaScript MVW Framework. It was developed with the motive to encounter the challenges of creating single page applications. There are several versions of angular such as Angular 2+, Angular 2 or ng2. Angular is the rewritten, mostly incompatible successor to AngularJS which means AngularJS is the oldest framework.
React: React was developed by Facebook in March 2013. It is a JavaScript library that is used for building user interfaces. React creates large web applications and also provides speed, scalability, and simplicity.
Vue Js: Launched in February 2014, Vue is the most famous and rapidly growing framework in JS field. Vue is an intuitive, fast and composable MVVM for building interactive interfaces. It is extremely adaptable and several JavaScript libraries make use of this. Vue is also a web application framework that helps in making advanced single page applications.
15. What is the use of the arrow function in ReactJS?
Ans:
Arrow functions are extremely important for React operations. It prevents these bugs. Arrow functions make it easier to predict the behavior of these bugs when passed as callbacks. They don’t redefine the value of this within their function body. Hence, prevents bugs caused by the use of this within callbacks.
16. Explain the purpose of providing reflection ().
Ans:
Every efficiency must be provided. It is a single opposite element that represents its own DOM components. If more than one HTML element is supplied, they should be linked together in a fuzzy index like <form>, <group>, <div>. This function is pure, i.e. it will be returned to the same conclusion every time it is implemented.
17. What is the purpose of render() function in ReactJS?
Ans:
render() function is used to update the UI. For this, you have to create a new element and send it to ReactDOM.render(). React elements are immutable and once you create an element, you cannot change its attributes. Thus, elements are like a single frame and it depicts the UI at some point. ReactDOM.render() controls the content of the container node you pass and if there is any DOM element already present in it then it would be replaced when first called.
18. What is React Router?
Ans:
React Router is a routing library developed on top of the react which is employed to create the routing in react apps. In single page websites, there is only a single HTML page, we are reusing the same HTML page to render the various components based on the navigation. But in multi-page websites, you will get a totally new page from the server when you operate.
19. Explain the role of Reducer?
Ans:
Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking 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. It returns the previous state as it is if no work needs to be done.
20. How are forms created in React?
Ans:
React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.
21. Can you use ref inside a functional component?
Ans:
No, you cannot use ref inside a functional component since functional components are stateless and they produce the same output. However, ref attribute is used to get the reference to a DOM node or an instance of a component in React and then manipulate its instance.
22. Why is virtual dom faster?
Ans:
Virtual dom is faster because it uses:
- Efficient diff algorithm
- Batched update operations
- Efficient update of subtree only
- Uses observable instead of dirty checking to detect a change
Note:
ReactJS maintains two virtual DOMs, one of the updated state Virtual DOM and another with the prior state Virtual DOM.
23. What is Props?
Ans:
Props are Properties of React. It is immutable Properties of React, In another word you can’t change the value of props. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. We can also say, Props are communication channels of two different components. It is used to render the dynamically generated data and helps to maintain the unidirectional data flow.
24. Compare props and state?
Ans:
Following are a few noticeable points for a quick comparison of prop and state:
- Both Props and State receive initial value from the parent component
- In-State, the parent component can change the value, while in case of props it is not so.
- Default values can be set in both state and prop
- Components can be changed from inside in case of State while this cannot be done in Props
- The initial value can be set for child component in both of the cases
25. Do you know Lerna or what a monorepo is?
Ans:
Lerna is a tool used to handle mono repositories and package dependencies. Essentially, instead of having a large monolithic application, we break it down into small independent packages kept in one repository.
26. What are the actions and action creators?
Ans:
An action is an object with a mandatory type field, it usually also has a payload which is the data related to the action. An action creator is a function which returns an action.
27. What is hoisting?
Ans:
A common answer is: hoisting is a mechanism which moves all declarations to the top of the execution scope. A good answer is understanding that JavaScript compiles your code before execution. When the compiler enters an execution context, it will start lexing (splitting your code) and analyzing the code while creating a list out of the declarations it finds. Each time the compiler encounters a declaration, it will create a binding to it and each time it encounters an assignment or evaluation it will ask the current scope for the binding, if it can’t find the binding, it will go up until it reaches the global scope. If you have a strict mode on, you will get an error and if you use the good old es5 it will create a new binding for you. This is why you are able to assign to a variable which wasn’t declared before. Anyway, after running through some steps, it will generate some compiled code which can be then executed.
28. What is React Fiber?
Ans:
Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.
29. What is Lifting State Up in React?
Ans:
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. That means 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.
30. What is reconciliation?
Ans:
When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.
31. What are the limitations of React?
Ans:
- React is just a view library, not a full framework.
- There is a learning curve for beginners who are new to web development.
- Integrating React into a traditional MVC framework requires some additional configuration.
- The code complexity increases with inline templating and JSX.
- Too many smaller components leading to over engineering or boilerplate.
32. Explain the term stateless components
Ans:
Stateless components are pure functions that render DOM-based solely on the properties provided to them.
33. What is the mental model of redux-saga?
Ans:
Saga is like a separate thread in your application, that’s solely responsible for side effects. redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.
34 . What are the popular animation packages in the React ecosystem?
Ans:
Popular animation package in React ecosystem are:
- React Motion
- React Transition Group
35. What is the benefit of strict mode?
Ans:
This will be helpful in the below cases
- Identifying components with unsafe lifecycle methods.
- Warning about legacy string ref API usage.
- Detecting unexpected side effects.
- Detecting legacy context API.
- Warning about deprecated findDOMNode usage
36. What is a dispatcher?
Ans:
A dispatcher is a central hub of the app where you will receive actions and broadcast payload to registered callbacks.
37. What is meant by callback function? What is its purpose?
Ans:
A callback function should be called when setState has finished, and the component is re-rendered. As the setState is asynchronous, which is why it takes in a second callback function.
38. Explain the term high order component
Ans:
A higher-order component also shortly known as HOC is an advanced technique for reusing component logic. It is not a part of the React API, but they are a pattern which emerges from React’s compositional nature.
39. Explain the Representational segment
Ans:
A presentational part is a segment which allows you to render HTML. The segment’s capacity is presentational in markup.
40. What are Props in react js?
Ans:
Props mean properties, which is a way of passing data from parent to child. We can say that props are just a communication channel between components. It is always moving from parent to child component.
41. What is the use of a super keyword in React?
Ans:
The super keyword helps you to access and call functions on an object’s parent.
42. Explain yield catchphrase in JavaScript
Ans:
The yield catchphrase is utilized to delay and resume a generator work, which is known as yield catchphrase.
43. Name two types of React component
Ans:
Two types of react Components are:
- Function component
- Class component
44. Explain error boundaries?
Ans:
Error boundaries help you to catch Javascript error anywhere in the child components. They are most used to log the error and show a fallback UI.
45. State the main difference between Pros and State
Ans:
The main difference between the two is that the State is mutable and Pros are immutable.
46. Explain pure components in React js
Ans:
Pure components are the fastest components which can replace any component with only a render(). It helps you to enhance the simplicity of the code and performance of the application.
47. What kind of information controls a segment in React?
Ans:
There are mainly two sorts of information that control a segment: State and Props
- State: State information that will change, we need to utilize State.
- Props: Props are set by the parent and which are settled all through the lifetime of a part.
48. Real DOM vs Virtual DOM
Ans:
Browsers can only read JavaScript objects but JSX is not a regular JavaScript object. So to enable a browser to read JSX, first, we need to transform a JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.
49. What Are Redux Workflow Features?
Ans:
Reset:
Allow to reset the state of the store
Revert:
Roll back to the last committed state
Sweep:
All disabled actions that you might have fired by mistake will be removed
Commit:
It makes the current state the initial state
50. What Is The Typical Flow Of Data In A React + Redux App?
Ans:
Call-back from the UI component dispatches an action with a payload, these dispatched actions are intercepted and received by the reducers. This interception will generate a new application state. from here the actions will be propagated down through a hierarchy of components from Redux store. The below diagram depicts the entity structure of a redux+react setup.
51. Where Can Redux Be Used?
Ans:
Redux is majorly used as a combination with reacting. it also has the ability to get used with other view libraries too. some of the famous entities like AngularJS, Vue.js, and Meteor. can get combined with Redux easily. This is a key reason for the popularity of Redux in its ecosystem. So many articles, tutorials, middleware, tools, and boilerplates are available.
52. What Is Redux Change Of State?
Ans:
For a release of an action, a change in state to an application is applied, this ensures an intent to change the state will be achieved.
Example:
- The user clicks a button in the application.
- A function is called in the form of component
- So now an action gets dispatched by the relative container.
- This happens because the prop (which was just called in the container) is tied to an action dispatcher using mapDispatchToProps (in the container).
- Reducer on capturing the action it intern executes a function and this function returns a new state with specific changes.
- The state change is known by the container and modifies a specific prop in the component as a result of the mapStateToProps function.
53. How Distinct From Mvc And Flux?
Ans:
- As far as MVC structure is concerned the data, presentation and logical layers are well separated and handled. Here change to an application even at a smaller position may involve a lot of changes through the application. This happens because data flow exists bidirectional as far as MVC is concerned. Maintenance of MVC structures is hardly complex and Debugging also expects a lot of experience for it.
- Flux stands closely related to redux. A story based strategy allows capturing the changes applied to the application state, the event subscription, and the current state are connected by means of components. Call back payloads are broadcasted by means of Redux.
54. What Are The Benefits Of Redux?
Ans:
Maintainability:
Maintenance of Redux becomes easier due to strict code structure and organisation.
Organization:
Code organisation is very strict hence the stability of the code is high which intern increases the work to be much easier.
Server rendering: This is useful, particularly to the preliminary render, which keeps up a better user experience or search engine optimization. The server-side created stores are forwarded to the client side.
Developer tools:
It is Highly traceable so changes in position and changes in the application all such instances make the developers have a real-time experience.
Ease of testing:
The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is made of functions that used to be: small, pure and isolated.
55. How To Apply Validation On Props In Reactjs?
Ans:
When the application is running in development mode, React will automatically check for all props that we set on components to make sure they must correctly correct and right data type.
For instance, if we say a component has a Message prop which is a string and is required, React will automatically check and warn if it gets invalid string or number or boolean objects. For performance reasons this check is only done on dev environments and on production it is disabled so that rendering of objects is done in a fast manner .
Warning messages are generated easily using a set of predefined options such as:
- React.PropTypes.string
- React.PropTypes.number
- React.PropTypes.func
- React.PropTypes.node
- React.PropTypes.bool
56. What Is Reactjs-jsx?
Ans:
JSX (JavaScript XML), lets us build DOM nodes with HTML-like syntax. JSX is a preprocessor step which adds XML syntax to JavaScript.
Like XML, JSX tags have a tag name, attributes, and children JSX also has the same. If an attribute/property value is enclosed in quotes(“”), the value is said to be string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript expression. We can represent JSX as <HelloWorld/>.
57. Explain Basic Code Snippet Of Jsx With The Help Of A Practical Example?
Ans:
Your browsers do not understand JSX code natively, we need to convert it to JavaScript first which can be understood by our browsers. We have a plugin which handles including Babel 5’s in-browser ES6 and JSX transformer called browser.js.
Babel will understand and recognize JSX code in <script type=”text/babel”></script> tags and transform/convert it to normal JavaScript code.
In case of production we will need to pre-compile our JSX code into JS before deploying to the production environment so that our app renders faster.
58. Explain Various Flux Elements Including Action, Dispatcher, Store And View?
Ans:
Flux can be better explained by defining its individual components:
- Actions – They are helper methods that facilitate passing data to the Dispatcher.
- Dispatcher – It is Central hub of the app, it receives actions and broadcasts payloads to registered callbacks.
- Stores – It is said to be Containers for application state & logic that have callbacks registered to the dispatcher. Every store maintains a particular state and it will update when it is needed. It wakes up on a relevant dispatch to retrieve the requested data. It is accomplished by registering with the dispatcher when constructed. They are similar to models in a traditional MVC (Model View Controller), but they manage the state of many objects — it does not represent a single record of data like ORM models do.
- Controller Views – React Components grabs the state from Stores and passes it down through props to child components to view to render application.
59. Give An Example Of Using Events?
Ans:
- import React from ‘react’;
- import ReactDOM from ‘react-dom’;
- var StepCounter = React.createClass({
- getInitialState: function() { return {counter: this.props.initialCounter }; },
- handleClick: function() {
- this.setState({counter: this.state.counter + 1}); },
- render: function() {
- return <div onClick={this.handleClick}> OnClick Event, Click Here: {this.state.counter }</div>;
- }
- });
- ReactDOM.render(< StepCounter initialCounter={7}/>, document.getElementById(‘content’));
60. How To Use Events In Reactjs?
Ans:
React identifies every event so that it must have common and consistent behavior across all the browsers. Normally, in normal JavaScript or other frameworks, the onchange event is triggered after we have typed something into a Textfield and then “exited out of it”. In ReactJS we cannot do it in this way.
The explanation is typical and non-trivial:
*”<input type=”text” value=”dataValue”> renders an input textbox initialized with the value, “dataValue”.
When the user changes the input in the text field, the node’s value property will update and change. However, node.getAttribute(‘value’) will still return the value used at initialization time that is dataValue.
Form Events:
- onChange: onChange event watches input changes and updates state accordingly.
- onInput: It is triggered on input data
- onSubmit: It is triggered on the submit button.
Mouse Events:
- onClick: OnClick of any components event is triggered on.
- onDoubleClick: onDoubleClick of any component event is triggered on.
- onMouseMove: onMouseMove of any components, panel event is triggered on.
- onMouseOver: onMouseOver of any components, panel, divs event is triggered on.
Touch Events:
- onTouchCancel: This event is for canceling an event.
- onTouchEnd: Time Duration attached to touch of a screen.
- onTouchMove: Move during touch device .
- onTouchStart: On touching a device event is generated.
61. How To Use Forms In Reactjs?
Ans:
In React’s virtual DOM, HTML Input element presents an interesting problem. With the other DOM environment, we can render the input or textarea and thus allows the browser to maintain its state that is (its value). we can then get and set the value implicitly with the DOM API.
In HTML, form elements such as <input>, <textarea>, and <select> itself maintain their own state and update its state based on the input provided by user .In React, components’ mutable state is handled by the state property and is only updated by setState().
- HTML <input> and <textarea> components use the value attribute.
- HTML <input> checkbox and radio components, checked attribute is used.
- <option> (within <select>) components, selected attribute is used for select box.
62. What Are The Limitations Of Reactjs?
Ans:
Limitations of ReactJS:
- React is only for the view layer of the app so we still need the help of other technologies to get a complete tooling set for development.
- React is using inline templating and JSX. This can seem awkward to some developers.
- The library of React is too large.
- Learning curve for ReactJS may be steep.
63. How To Embed Two Components In One Component?
Ans:
- import React from ‘react’;
- class App extends React.Component {
- render() {
- return (
- <div>
- <Header/>
- <Content/>
- </div>
- );
- }
- }
- class Header extends React.Component {
- render() {
- return (
- <div>
- <h1>Header</h1>
- </div>
- );
- }
- }
64. When Reactjs Released?
Ans:
March 2013
65. What’s wrong with following code?
Ans:
Nothing isn’t right with it. It’s once in a while utilized and not outstanding, but rather you can likewise pass a function to setState that gets the past state and props and returns another state, similarly as we’re doing above. Furthermore, is nothing amiss with it, as well as effectively recommended in case you’re setting state in light of the previous state.
66. What are pure functional Components?
Ans:
- Traditional React Components as we have seen so far is making a class with class Example extends React. Component or React. create Class(). These make stateful components on the off chance that we at any point set the state (i.e. this. set State(), get Initial State(), or this.state = {} inside a constructor()).
- In the event that we have no expectation for a Component to require state, or to require lifecycle methods, we can really compose Components with a pure function, consequently the expression “pure function Component”:
67. What is the purpose of using the super constructor with a props argument?
Ans:
A child class constructor cannot make use of this reference until the super() method has been called. The same applies to ES6 sub-classes as well. The main reason for passing props parameter to super() call is to access this.props in your child constructors.
68. What is Lifting State Up in React?
Ans:
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. That means 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.
69. Passing functions between components in React and React Native?
Ans:
- I would stay away from such passing functions between components. I always use Flux architecture with ReactJs and React Native.
- Keep components just to render stuff by properties and sending new actions.
- You have a hard dependency between components. This stuff does not scale. It will be hard to maintain such code.
- What I personally do is just write actions, stores, dispatcher and don’t use any dependency on stuff like redux, because React Native is evolving rapidly and you never know if your dependencies will do it at the same speed.
70. Handling Multiple Platforms?
Ans:
- React Native gracefully handles multiple platforms. The vast majority of the React Native APIs are cross-platform, so you just need to write one React Native component, and it will work seamlessly on both iOS and Android. Facebook claims that its Ad Manager application has 87% code reuse across the two platforms, and I wrote a flashcard app without any platform-specific code at all.
- If you do want to write platform-specific code — due to different interaction guidelines on iOS and Android, for instance, or because you want to take advantage of a platform-specific API — that’s easy, too. React Native allows you to specify platform-specific versions of each component, which you can then integrate into the rest of your React Native application.
71. What is the difference between a Container and a Component?
Ans:
- The component is part of the React API. A Component is a class or function that describes part of a React UI.
- The container is an informal term for a React component that is connected to a redux store. Containers receive Redux state updates and dispatch actions, and they usually don’t render DOM elements; they delegate rendering to presentational child components.
72. What is ‘setState’ used for?
Ans:
When you issue a ‘setState’ command, an object is merged into the current state. After this is done, the UI is updated according to the new set state.
73. Enlist React limitations if you know any?
Ans:
Though React is a popular tool but has some limitations that are listed below:
- React is not a framework but a set of libraries.
- Designers take time to understand this library as it is very large in size
- For novice programmers, it can be difficult to understand this library
- Inline templating and JSX makes the coding somewhat complex
74. How do you handle method binding in components?
Ans:
There are more ways, we can bind the method in the render, in component Did Mount or use the preferred way, which is arrow functions.
75. What are closures and lexical scope?
Ans:
A closure is when a function is able to remember and access its lexical scope even when that function is executed outside of that scope. A good example of closures is currying, a commonly accepted answer is also responding that an inner function returned by an outer function has access to the variables of its outer function even after the outer function was called. Lexical scope is the scope model used by JavaScript which compared to dynamic scoping enables a lot of cool features. If someone also explains lexing time and goes into hoisting it is a big bonus.
76. How would your performance optimize a React app?
Ans:
- Developers who never met with performance issues would answer this differently than battle-hardened veterans. It should clearly indicate if you’re stuck with quoting articles, or you actually measured, iterated and fixed real performance issues in the past.
- Talking about micro-optimizations and broad ideas show the former while mentioning issues, measurements and development tools – that you used in the past – signals the latter.
- If you are experienced with performance optimization, do not start speaking about the general concepts. Get straight to the specific tools and methods you used.
77. What are your arch nemesis front-end issues?
Ans:
- If you are like me, you have issues that come up in every project. Mines are animation orchestration and complex routing patterns. I could speak hours about why I can’t get them right and what I hate about the libraries that I use.
- Letting you choose the topic keeps the conversation comfortable and it is a good check on the limits of your knowledge.
- Be honest if a question like this comes up. You can show a lot of expertise by reasoning about complex issues that you just can’t get right. We might even find a common enemy to hate.
78. Explain DOM diffing?
Ans:
When the components are rendered twice, Virtual Dom begins checking the modifications elements have got. They represent the changed element on the page simply. There are several other elements that don’t go through changes. To cut down the changes to the DOM as an outcome of user activities, DOM doffing is considered. It is generally done to boost the performance of the browser. This is the reason for its ability to perform all the tasks quickly.
79. e-Render on Changes?
Ans:
In addition to props, components can also have an internal state. The most prominent example of that behavior would be a click counter that updates its value when a button is pressed. The number of clicks itself would be saved in the state.
80. Is it possible to nest JSX elements into other JSX elements?
Ans:
It is possible. The process is quite similar to that of nesting the HTML elements. However, there are certain things that are different in this. You must be familiar with the source and destination elements to perform this task simply.
81. What is the typical use case of portals?
Ans:
React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context(z-index,position,opacity etc styles) and you need to visually “break out” of its container. For example, dialogs, global message notifications, hovercards, and tooltips.
82. What is your favorite React stack?
Ans:
Even though the tech stack varies from developer to developer, the most popular stack is used in react boilerplate project code. It mainly uses Redux and redux-saga for state management and asynchronous side-effects, react-router for routing purpose, styled-components for styling react components, axios for invoking REST api, and other supported stack such as webpack, reselect, ESNext, Babel. You can clone the project and start working on any new react project.
83. How to add a bootstrap for a react application?
Ans:
Bootstrap can be added to your React app in a three possible ways
- Using the Bootstrap CDN: This is the easiest way to add bootstrap. Add both bootstrap CSS and JS resources in a head tag.
Bootstrap as Dependency: If you are using a build tool or a module bundler such as Webpack, then this is the preferred option for adding Bootstrap to your React application
npm install bootstrap
- React Bootstrap Package: In this case, you can add Bootstrap to our React app by using a package that has rebuilt Bootstrap components to work particularly as React components. Below packages are popular in this category,
- react-bootstrap
- reactstrap
84. Is it recommended to use CSS In JS technique in React?
Ans:
React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate *.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries. But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option.
85. Do I need to rewrite all my class components with hooks?
Ans:
No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.
86. What are the drawbacks of MVW pattern?
Ans:
- The DOM manipulation is very expensive which causes applications to behave slowly and inefficiently.
- Due to circular dependencies, a complicated model was created around models and views.
- Lot of data changes happen for collaborative applications(like Google Docs).
- No way to do undo (travel back in time) easily without adding so much extra code.
87. Can I dispatch an action in the reducer?
Ans:
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.
88. What is Redux?
Ans:
Redux is a predictable state container for JavaScript apps based on the Flux design pattern. Redux can be used together with React, or with any other view library. It is tiny (about 2kB) and has no dependencies.
89. What is the purpose of the ReactTestUtils package?
Ans:
ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.
90. What is Jest?
Ans:
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.
91. What are the advantages of Jest over Jasmine?
Ans:
There are couple of advantages compared to Jasmine:
- Automatically finds tests to execute in your source code.
- Automatically mocks dependencies when running your tests.
- Allows you to test asynchronous code synchronously.
- Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line.
- Runs tests in parallel processes so that they finish sooner.
92. What is React Intl?
Ans:
The React Intl 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. React Intl is part of FormatJS which provides bindings to React via its components and API.
93. What are the main features of React Intl?
Ans:
- Display numbers with separators.
- Display dates and times correctly.
- Display dates relative to “now”.
- Pluralize labels in strings.
- Support for 150+ languages.
- Runs in the browser and Node.
- Built on standards.
94. What is React Router?
Ans:
React Router is a powerful routing library built on top of React that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what’s being displayed on the page.
95. How is the React Router different from a history library?
Ans:
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 (React Native) and unit testing with Node.
96. What are the <Router> components of React Router v4?
Ans:
React Router v4 provides below 3 <Router> components:
- <BrowserRouter>
- <HashRouter>
- <MemoryRouter>
The above components will create browser, hash, and memory history instances. React Router v4 makes the properties and methods of the history instance associated with your router available through the context in the router object.
97. What is the use of the react-dom package?
Ans:
The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:
- render()
- hydrate()
- unmountComponentAtNode()
- findDOMNode()
- createPortal()
98. How events are different in React?
Ans:
Handling events in React elements has some syntactic differences:
- React event handlers are named using camelCase, rather than lowercase.
- With JSX you pass a function as the event handler, rather than a string.
99. What will happen if you use setState() in constructor?
When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get an error like this: Can only update a mounted or mounting component. So we need to use this.state to initialize variables inside the constructor.