Reactjs is the most demanding skill now a days.
React developers are highly paid professionals now a days.
So if you are going to appear in an interview for a Front End Developer or a Full-stack Developer, you should know that what will be questions that will be asked by interviewer.
Although a deep knowledge is required to crack any interview, but these Reactjs Interview Questions and Answers may add some spark in your interviews.
These are the fundamental questions and can be asked at any level of experience. So be prepared for your interview.
What is React?
React is an open-source frontend JavaScript library which is used for building user interfaces especially for single page applications.
It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.
What are the major features of React?
The major features of React are:
- It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
- Supports server-side rendering.
- Follows Unidirectional data flow or data binding.
- Uses reusable/composable UI components to develop the view.
What is JSX?
JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.
In the example below the text inside the h1 tag returns as JavaScript function to the render function.
class App extends React.Component { render() { return( <div> <h1>{'Welcome to React world!'}</h1> </div> ) } }
What are Pure Components?
React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Components on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.
What is the difference between state and props?
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to components. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.
What is the use of refs?
The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need direct access to the DOM element or an instance of a component.
What is Virtual DOM?
The Virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the “real” DOM. It’s a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.
What is the difference between Shadow DOM and Virtual DOM?
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
What is React Fiber?
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.
What is the main goal of React Fiber?
The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.
What are controlled components?
A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function.
For example, to write all the names in uppercase letters, we use handleChange as below,
handleChange(event) { this.setState({value: event.target.value.toUpperCase()}) }
How to create props proxy for HOC components?
You can add/edit props passed to the component using props proxy pattern like this:
function HOC(WrappedComponent) { return class Test extends Component { render() { const newProps = { title: 'New Header', footer: false, showFeatureX: false, showFeatureY: true } return <WrappedComponent {...this.props} {...newProps} /> } } }
What is context?
Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.
const {Provider, Consumer} = React.createContext(defaultValue)
What is a child prop?
Children is a prop (this.prop.children) that allows you to pass components as data to other components, just like any other prop you use. Component tree put between the component’s opening and closing tag will be passed to that component as children prop.
There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray. A simple usage of children prop looks as below,
const MyDiv = React.createClass({ render: function() { return <div>{this.props.children}</div> } }) ReactDOM.render( <MyDiv> <span>{'Hello'}</span> <span>{'World'}</span> </MyDiv>, node )
What is reconciliation?
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.
How to set a state with a dynamic key name?
If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.
handleInputChange(event) { this.setState({ [event.target.id]: event.target.value }) }
Why does React use className over class attribute?
class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class. Pass a string as the className prop.
render() { return <span className={'menu navigation-menu'}>{'Menu'}</span> }
Why are fragments better than container divs?
Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
Some CSS mechanisms like Flexbox and CSS Grid have special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
The DOM Inspector is less cluttered.
What are stateless components?
If the behavior is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid this keyword altogether.
What are the advantages of React?
Increases the application’s performance with Virtual DOM.
JSX makes code easy to read and write.
It renders both on client and server side (SSR).
Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
Easy to write unit and integration tests with tools such as Jest.
What are the limitations of React?
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.
How are error boundaries handled in React v15?
React v15 provided very basic support for error boundaries using the unstable_handleError method. It has been renamed to componentDidCatch in React v16.
What is the purpose of the render method of react-dom?
This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into a container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.
ReactDOM.render(element, container[, callback])
If the optional callback is provided, it will be executed after the component is rendered or updated.
How to use innerHTML in React?
The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.
In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:
function createMarkup() { return { __html: 'First · Second' } } function MyComponent() { return <div dangerouslySetInnerHTML={createMarkup()} /> }
How are different types of events in React?
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.
What will happen if you use setState() in the 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 What will happen if you use setState() in constructor?What will happen if you use setState() in the constructor?I need to use this.state to initialize variables inside the constructor.
How do you conditionally render components?
In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.
const MyComponent = ({ name, address }) => ( <div> <h2>{name}</h2> {address && <p>{address}</p> } </div> ) If you need an if-else condition then use a ternary operator. const MyComponent = ({ name, address }) => ( <div> <h2>{name}</h2> {address ? <p>{address}</p> : <p>{'Address is not available'}</p> } </div> )