39+ Advanced React Interview Questions (SOLVED) You Must Clarify (2020 Update)
Tags: react, career, interview
Published: 2019-11-04 02:31:07

---
title: 39+ Advanced React Interview Questions (SOLVED) You Must Clarify (2020 Update)
published: true
description: 39+ Advanced React Interview Questions (SOLVED) You Must Clarify (2020 Update)
tags: #react #career #interview
canonical_url: https://www.fullstack.cafe/blog/react-js-interview-questions
cover_image: https://images.pexels.com/photos/1569002/pexels-photo-1569002.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500
---

The average React Js Developer salary in USA is $125,000 per year or $64.10 per hour. Entry level positions start at $63,050 per year while most experienced workers make up to $195,000 per year. Follow along to learn most advanced React Interview Questions for your next tech interview.

> 🔴 Originally published on [FullStack.Cafe - Kill Your Tech & Coding Interview](https://www.fullstack.cafe/?utm_source=dev&utm_medium=blog)

### Q1: What is virtual DOM?
> Topic: **React**<br/>Difficulty: ⭐

**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.

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q2: What are the differences between a class component and functional component?
> Topic: **React**<br/>Difficulty: ⭐⭐

- **Class components** allows you to use additional features such as local state and lifecycle hooks. Also, to enable your component to have direct access to your store and thus holds state.

- When your component just receives props and renders them to the page, this is a **stateless component**, for which a pure function can be used. These are also called dumb components or presentational components.

🔗 **Source:** [github.com/Pau1fitz](https://github.com/Pau1fitz/react-interview)
### Q3: What are refs used for in React?
> Topic: **React**<br/>Difficulty: ⭐⭐

*Refs* are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.

```js
class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}
```
Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function.

It’s often misconstrued that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.

```js
function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}
```

🔗 **Source:** [github.com/Pau1fitz](https://github.com/Pau1fitz/react-interview)
### Q4: Describe how events are handled in React.
> Topic: **React**<br/>Difficulty: ⭐⭐

In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent, which is React’s cross-browser wrapper around the browser’s native event. These synthetic events have the same interface as native events you’re used to, except they work identically across all browsers.

What’s mildly interesting is that React doesn’t actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn’t need to worry about keeping track of event listeners when updating the DOM.

🔗 **Source:** [tylermcginnis.com](https://tylermcginnis.com/react-interview-questions/)
### Q5: What is the difference between state and props?
> Topic: **React**<br/>Difficulty: ⭐⭐

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 component. i.e, 
* Props get passed to the component similar to function parameters 
* state is managed within the component similar to variables declared within a function.

🔗 **Source:** [https://github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q6: How to create refs?
> Topic: **React**<br/>Difficulty: ⭐⭐

**Refs** are created using `React.createRef()` method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property with in constructor.
```js
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}
```
And:
```js
class UserForm extends Component {
  handleSubmit = () => {
    console.log("Input Value is: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} /> // Access DOM input in handle submit
        <button type='submit'>Submit</button>
      </form>
    )
  }
}
```
We can also use it in functional components with the help of closures.

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q7: What are Higher-Order components?
> Topic: **React**<br/>Difficulty: ⭐⭐

A higher-order component **(HOC)** is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature
We call them as **“pure’ components”**  because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.
```js
const EnhancedComponent = higherOrderComponent(WrappedComponent);
```
HOC can be used for many use cases as below,

1. Code reuse, logic and bootstrap abstraction
2. Render High jacking
3. State abstraction and manipulation
4. Props manipulation

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q8: What is the purpose of using super constructor with props argument?
> Topic: **React**<br/>Difficulty: ⭐⭐

A child class constructor cannot make use of **this** reference until `super()` method has been called. The same applies for ES6 sub-classes as well. The main reason of passing props parameter to super() call is to access this.props in your child constructors.

**Passing props:**
```js
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props);  // Prints { name: 'sudheer',age: 30 }
    }
}
```
**Not passing props:**
```js
class MyComponent extends React.Component {
    constructor(props) {
        super();
        console.log(this.props); // Prints undefined
        // But Props parameter is still available
        console.log(props); // Prints { name: 'sudheer',age: 30 }
    }

    render() {
        // No difference outside constructor
        console.log(this.props) // Prints { name: 'sudheer',age: 30 }
    }
}
```

The above code snippets reveals that this.props behavior is different only with in the constructor. It would be same outside the constructor.

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q9: What are controlled components?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

In HTML, form elements such as `<input>`, `<textarea>`, and `<select>` typically maintain their own state and update it based on user input. When a user submits a form the values from the aforementioned elements are sent with the form. With React it works differently. The component containing the form will keep track of the value of the input in it's state and will re-render the component each time the callback function e.g. `onChange` is fired as the state will be updated. An input form element whose value is controlled by React in this way is called a **controlled component**.

🔗 **Source:** [github.com/Pau1fitz](https://github.com/Pau1fitz/react-interview)
### Q10: What is equivalent of the following using React.createElement?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

**Question**:

```js
const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);
```
What is equivalent of the following using `React.createElement`?

**Answer**:

```js
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);
```

🔗 **Source:** [github.com/Pau1fitz](https://github.com/Pau1fitz/react-interview)
### Q11: What can you tell me about JSX?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

When Facebook first released React to the world, they also introduced a new dialect of JavaScript called JSX that embeds raw HTML templates inside JavaScript code. JSX code by itself cannot be read by the browser; it must be transpiled into traditional JavaScript using tools like Babel and webpack. While many developers understandably have initial knee-jerk reactions against it, JSX (in tandem with ES2015) has become the defacto method of defining React components.

```js
class MyComponent extends React.Component {
  render() {
    let props = this.props;  
    return (
      <div className="my-component">
      <a href={props.url}>{props.name}</a>
      </div>
    );
  }
}
```

🔗 **Source:** [codementor.io](https://www.codementor.io/blog/5-essential-reactjs-interview-questions-du1084ym1)
### Q12: Given the code defined above, can you identify two problems?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

Take a look at the code below:

```js
class MyComponent extends React.Component {
  constructor(props) {
    // set the default internal state
    this.state = {
      clicks: 0
    };
  }

  componentDidMount() {
    this.refs.myComponentDiv.addEventListener('click', this.clickHandler);
  }

  componentWillUnmount() {
    this.refs.myComponentDiv.removeEventListener('click', this.clickHandler);
  }

  clickHandler() {
    this.setState({
      clicks: this.clicks + 1
    });
  }

  render() {
    let children = this.props.children;

    return (
      <div className="my-component" ref="myComponentDiv">
      <h2>My Component ({this.state.clicks} clicks})</h2>
      <h3>{this.props.headerText}</h3>
    {children}
    </div>
    );
  }
}

```
Given the code defined above, can you identify two problems?

**Answer:**
1.  The constructor does not pass its props to the super class. It should include the following line:

```js
constructor(props) {
  super(props);
  // ...
}
  ```  

2.  The event listener (when assigned via `addEventListener()`) is not properly scoped because [ES2015 doesn’t provide autobinding](https://facebook.github.io/react/docs/reusable-components.html#no-autobinding). Therefore the developer can re-assign `clickHandler` in the constructor to include the correct binding to this:

```js
constructor(props) {
  super(props);
  this.clickHandler = this.clickHandler.bind(this);
  // ...
}
```

🔗 **Source:** [codementor.io](https://www.codementor.io/blog/5-essential-reactjs-interview-questions-du1084ym1)
### Q13: Why should not we update the state directly?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

If you try to update state directly then it won’t re-render the component.

```js
    //Wrong
    This.state.message =”Hello world”;
```

Instead use `setState()` method. It schedules an update to a component’s state object. When state changes, the component responds by re-rendering

```js
    //Correct
    This.setState({message: ‘Hello World’});
```

**Note:** The only place you can assign the state is constructor.


🔗 **Source:** [https://github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q14: What are the different phases of ReactJS component lifecycle?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

There are four different phases of React component’s lifecycle:
1. **Initialization:** In this phase react component prepares setting up the initial state and default props.
2. **Mounting:** The react component is ready to mount in the browser DOM. This phase covers **componentWillMount** and **componentDidMount** lifecycle methods.
3. **Updating:** In this phase, the component get updated in two ways, sending the new props and updating the state. This phase covers **shouldComponentUpdate, componentWillUpdate and componentDidUpdate** lifecycle methods.
4. **Unmounting:** In this last phase, the component is not needed and get unmounted from the browser DOM. This phase include **componentWillUnmount** lifecycle method.

<div class="text-center">
<img src="https://github.com/sudheerj/reactjs-interview-questions/raw/master/images/phases.png" class="img-fluid"/>
</div>

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q15: What are the lifecycle methods of ReactJS?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

-	**componentWillMount:** Executed before rendering and is used for App level configuration in your root component.
-	**componentDidMount:** Executed after first rendering and here all AJAX requests, DOM or state updates, and set up eventListeners should occur.
-	**componentWillReceiveProps:** Executed when particular prop updates to trigger state transitions.
-	**shouldComponentUpdate:** Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a rerender if component receives new prop.
-	**componentWillUpdate:** Executed before re-rendering the component when there are pros & state changes confirmed by shouldComponentUpdate  which returns true.
-	**componentDidUpdate:** Mostly it is used to update the DOM in response to prop or state changes.
-   **componentWillUnmount:** It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.


🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q16: What do these three dots (...) in React do?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

What does the ... do in this React (using JSX) code and what is it called?

```html
<Modal {...this.props} title='Modal heading' animation={fal
```

---
That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015).

For instance, if this.props contained a: 1 and b: 2, then
```html
<Modal {...this.props} title='Modal heading' animation={false}>
```
would be the same as:
```html
<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
```

Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:

```js
this.setState(prevState => {
    return {foo: {...prevState.foo, a: "updated"}};
});
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/31048953/what-do-these-three-dots-in-react-do)
### Q17: What are advantages of using React Hooks?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props. Hooks allow to easily manipulate the state of our functional component without needing to convert them into class components.

Hooks don’t work inside classes (because they let you use React without classes). By using them, we can totally avoid using lifecycle methods, such as `componentDidMount`, `componentDidUpdate`, `componentWillUnmount`. Instead, we will use built-in hooks like `useEffect` .

🔗 **Source:** [hackernoon.com](https://hackernoon.com/react-hooks-usestate-using-the-state-hook-89ec55b84f8c)
### Q18: What are React Hooks?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

**Hooks** are a new addition in React 16.8. They let you use state and other React features without writing a class. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

🔗 **Source:** [reactjs.org](https://reactjs.org/docs/hooks-overview.html)
### Q19: What is useState() in React?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

Explain what is the use of `useState(0)` there:
```js
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};
```

---
`useState` is one of build-in react hooks. `useState(0)` returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. 

We can use the `setCounter` method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/53165945/what-is-usestate-in-react)
### Q20: What is StrictMode in React?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

React's StrictMode is sort of a helper component that will help you write better react components, you can wrap a set of components with `<StrictMode />` and it'll basically:

* Verify that the components inside are following some of the recommended practices and warn you if not in the console.
* Verify the deprecated methods are not being used, and if they're used strict mode will warn you in the console.
* Help you prevent some side effects by identifying potential risks.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/53183362/what-is-strictmode-in-react)
### Q21: Why do class methods need to be bound to a class instance?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

In JavaScript, the value of `this` changes depending on the current context. Within React class component methods, developers normally expect this to refer to the current instance of a component, so it is necessary to _bind_ these methods to the instance. Normally this is done in the constructor—for example:

```js
class SubmitButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormSubmitted: false
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit() {
    this.setState({
      isFormSubmitted: true
    });
  }

  render() {
    return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
  }
}
```

🔗 **Source:** [toptal.com](https://www.toptal.com/react/interview-questions)
### Q22: What is prop drilling and how can you avoid it?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐

When building a React application, there is often the need for a deeply nested component to use data provided by another component that is much higher in the hierarchy. The simplest approach is to simply pass a prop from each component to the next in the hierarchy from the source component to the deeply nested component. This is called **prop drilling**.

The primary disadvantage of prop drilling is that components that should not otherwise be aware of the data become unnecessarily complicated and are harder to maintain.

To avoid prop drilling, a common approach is to use React context. This allows a `Provider` component that supplies data to be defined, and allows nested components to consume context data via either a `Consumer` component or a `useContext` hook.

🔗 **Source:** [toptal.com](https://www.toptal.com/react/interview-questions)
### Q23: Describe Flux vs MVC?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

Traditional MVC patterns have worked well for separating the concerns of data (Model), UI (View) and logic (Controller) — but MVC architectures frequently encounter two main problems:

*   **Poorly defined data flow:** The cascading updates which occur across views often lead to a tangled web of events which is difficult to debug.
    
*   **Lack of data integrity:** Model data can be mutated from anywhere, yielding unpredictable results across the UI.

With the Flux pattern complex UIs no longer suffer from cascading updates; any given React component will be able to reconstruct its state based on the data provided by the store. The Flux pattern also enforces data integrity by restricting direct access to the shared data.

🔗 **Source:** [codementor.io](https://www.codementor.io/blog/5-essential-reactjs-interview-questions-du1084ym1)
### Q24: What is the difference between a controlled component and an uncontrolled component?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

* A **controlled component** is a component where React is in control and is the single source of truth for the form data. 
* An **uncontrolled component** is where your form data is handled by the DOM, instead of inside your React component.

Though uncontrolled components are typically easier to implement since you just grab the value from the DOM using refs, it’s typically recommended that you favor controlled components over uncontrolled components. The main reasons for this are that controlled components support instant field validation, allow you to conditionally disable/enable buttons, enforce input formats, and are more “the React way”.


🔗 **Source:** [github.com/Pau1fitz](https://github.com/Pau1fitz/react-interview)
### Q25: What is wrong with this code?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

**Questions:**

What is wrong with this code?
```js
this.setState((prevState, props) => {
  return {
    streak: prevState.streak + props.count
  }
})
```
**Answer:**

Nothing is wrong with it. It’s rarely used and not well known, but you can also pass a function to `setState` that receives the previous state and props and returns a new state, just as we’re doing above. And not only is nothing wrong with it, but it’s also actively recommended if you’re setting state based on previous state.

🔗 **Source:** [tylermcginnis.com](https://tylermcginnis.com/react-interview-questions/)
### Q26: What is the React context?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

It's an experimental API that allows you to pass data down through a tree of components without having to use props.

🔗 **Source:** [github.com/WebPredict](https://github.com/WebPredict/react-interview-questions)
### Q27: What is React Fiber?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

**Fiber** is the new reconciliation engine or reimplementation core algorithm in React 16. Its main goal is to enable incremental rendering of the virtual DOM.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.

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.

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q28: How to apply validation on Props in ReactJS?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

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 right correct and right data type. For incorrect type, it will generate warning messages in the console for development mode whereas it is disabled in production mode due performance impact. The mandatory prop is defined with isRequired.

The set of predefined prop types are below

1. `React.PropTypes.string`
2. `React.PropTypes.number`
3. `React.PropTypes.func`
4. `React.PropTypes.node`
5. `React.PropTypes.bool`

For example, we define propTypes for user component as below,
```js
import PropTypes from 'prop-types';

class User extends React.Component {
  render() {
    return (
      <h1>Welcome, {this.props.name}</h1>
      <h2>Age, {this.props.age}
    );
  }
}

User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired

};
```

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q29: What is the difference between ReactJS and Angular?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

| ReactJS | Angular |
|---- | ---------
| React is a Library and has only the View layer  | Angular is a Framework and has complete MVC functionality |
| React handle rendering on the server side | Angular JS render on the client side but Angular 2 and above render on the server side |
| In React, HTML is written in JS which can be confusing| Angular follows the template approach for HTML, which makes code shorter and easy to understand.|
| React native, which is a React type to build mobile applications are faster and more stable | Ionic, Angular’s mobile native app is relatively less stable and slower|
| In React, data flows only in one way and hence debugging is easy | In Angular, data flows both way i.e it has two-way data binding between children and parent and hence debugging is often difficult |

🔗 **Source:** [github.com/sudheerj](https://github.com/sudheerj/reactjs-interview-questions)
### Q30: What is the difference between using constructor vs getInitialState in React?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

The difference between constructor and getInitialState is the difference between ES6 and ES5 itself. You should initialize state in the constructor when using ES6 classes, and define the `getInitialState` method when using `React.createClass`.
```js
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = { /* initial state */ };
      }
    }
```

is equivalent to 

```js
    var MyComponent = React.createClass({
      getInitialState() {
        return { /* initial state */ };
      },
    });
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r)
### Q31: When is it important to pass props to super(), and why?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

The only one reason when one needs to pass props to `super()` is when you want to access `this.props` in constructor:

```js
class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}
```
Not passing:
```js
class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}
```
Note that passing or not passing props to super has no effect on later uses of this.props outside constructor.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r)
### Q32: How to conditionally add attributes to React components?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

Is there a way to only add attributes to a React component if a certain condition is met?

---
For certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:
```js
var InputComponent = React.createClass({
    render: function() {
        var required = true;
        var disabled = false;

        return (
            <input type="text" disabled={disabled} required={required} />
        );
    }
});
```
will result in:
```html
<input type="text" required>
```
Another possible approach is:
```js
var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/31163693/how-to-conditionally-add-attributes-to-react-components)
### Q33: Do Hooks replace render props and higher-order components?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

Often, render props and higher-order components render only a single child. React team thinks _Hooks are a simpler way to serve this use case_. 

There is still a place for both patterns (for example, a virtual scroller component might have a renderItem prop, or a visual container component might have its own DOM structure). But in most cases, Hooks will be sufficient and can help reduce nesting in your tree.



🔗 **Source:** [reactjs.org](https://reactjs.org/docs/hooks-faq.html)
### Q34: How would you go about investigating slow React application rendering?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

One of the most common issues in React applications is when components _re-render unnecessarily_. There are two tools provided by React that are helpful in these situations:

* `React.memo()`: This prevents unnecessary re-rendering of function components
* `PureComponent`: This prevents unnecessary re-rendering of class components

Both of these tools rely on a shallow comparison of the props passed into the component—if the props have not changed, then the component will not re-render. While both tools are very useful, the shallow comparison brings with it an additional performance penalty, so both can have a negative performance impact if used incorrectly. By using the React Profiler, performance can be measured before and after using these tools to ensure that performance is actually improved by making a given change.

🔗 **Source:** [toptal.com](https://www.toptal.com/react/interview-questions)
### Q35: When would you use StrictMode component in React?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐

I've found it especially useful to implement strict mode when I'm working on new code bases and I want to see what kind of code/components I'm facing. Also if you're on bug hunting mode, sometimes it's a good idea to wrap with <StrictMode /> the components/blocks of code you think might be the source of the problem.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/53183362/what-is-strictmode-in-react)
### Q36: What is a pure function?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐⭐

A *Pure function* is a function that doesn't depend on and doesn't modify the states of variables out of its scope. Essentially, this means that a pure function will always return the same result given same parameters.

🔗 **Source:** [github.com/Pau1fitz](https://github.com/Pau1fitz/react-interview)
### Q37: How does React renderer work exactly when we call setState? 
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐⭐

There are two steps of what we may call "render":

 1. Virtual DOM render: when *render* method is called it returns a new *virtual dom* structure of the component. This *render* method is called always when you call *setState()*, because *shouldComponentUpdate* always returns true by default. So, by default, there is no optimization here in React.

 2. Native DOM render: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/24718709/reactjs-does-render-get-called-any-time-setstate-is-called)
### Q38: What is the key architectural difference between a JavaScript library such as React and a JavaScript framework such as Angular?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐⭐

React enables developers to render a user interface. To create a full front-end application, developers need other pieces, such as state management tools like Redux.

Like React, Angular enables developers to render a user interface, but it is a “batteries included” framework that includes prescriptive, opinionated solutions to common requirements like state management.

While there are many other considerations when comparing React and Angular specifically, this key architectural difference means that:

* Using a library such as React can give a project a greater ability to evolve parts of the system—again for example, state management—over time, when new solutions are created by the open source community.
* Using a framework such as Angular can make it easier for developers to get started and can also simplify maintenance.

🔗 **Source:** [toptal.com](https://www.toptal.com/react/interview-questions)
### Q39: How to avoid the need for binding in React?
> Topic: **React**<br/>Difficulty: ⭐⭐⭐⭐⭐

There are several common approaches used to avoid methods binding in React:

1. Define Your Event Handler as an Inline Arrow Function
```js
class SubmitButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormSubmitted: false
    };
  }

  render() {
    return (
      <button onClick={() => {
        this.setState({ isFormSubmitted: true });
      }}>Submit</button>
    )
  }
}
```
2. Define Your Event Handler as an Arrow Function Assigned to a Class Field
```js
class SubmitButton extends React.Component {
  state = {
    isFormSubmitted: false
  }

  handleSubmit = () => {
    this.setState({
      isFormSubmitted: true
    });
  }

  render() {
    return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
  }
}
```
3. Use a Function Component with Hooks
```js
const SubmitButton = () => {
  const [isFormSubmitted, setIsFormSubmitted] = useState(false);

  return (
    <button onClick={() => {
        setIsFormSubmitted(true);
    }}>Submit</button>
  )
};
```

🔗 **Source:** [toptal.com](https://www.toptal.com/react/interview-questions)

> *Thanks 🙌 for reading and good luck on your interview!* <br/>*Please share this article with your fellow devs if you like it!* <br/>*Check more FullStack Interview Questions & Answers on 👉 [www.fullstack.cafe](https://www.fullstack.cafe)*