Clue Mediator

React Interview Questions and Answers - Part 2

πŸ“…January 3, 2022

Frequently asked React Interview Questions and Answers for freshers as well as experienced developers.

React Interview Questions

List of React Interview Questions and Answers

  1. Why should we never update React State directly?
  2. When to use React setState callback?
  3. Can you update props in react?
  4. What is the difference between HTML and React event handling?
  5. How to bind methods or event handlers in JSX?
  6. How to pass a parameter to an event handler or callback?
  7. What are synthetic events in React?
  8. What is event pooling in React?
  9. What is "key" prop and what is the benefit of using it in arrays of elements?
  10. What are inline conditional expressions?

1. Why should we never update React State directly?

When you update the state directly like given below then it won't re-render the component.

// Incorrect
this.state.message = "Clue Mediator";

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

// Correct
this.setState({ message: "Clue Mediator"});

Note: You can directly assign to the state object either in the constructor or using the latest javascript's class field declaration syntax.

2. When to use React setState callback?

The callback function is invoked when the setState finished and the component gets rendered. Since `setState()` is asynchronous, the callback function is used for any post action.

setState({ message: "Clue Mediator" }, () => {
  console.log('The message has updated and component re-rendered');
});

Note: It is recommended to use the lifecycle method rather than this callback function.

3. Can you update props in react?

You can’t update props in react js because props are read-only. Moreover, you can not modify props received from parent to child.

4. What is the difference between HTML and React event handling?

  • Naming convention:

    HTML – Event names are written in lowercase like `onclick`, `onsubmit`, etc.

    <button onclick="myFunction()">Click me</button>
    

    React – It follows camelCase convention.

    <button onclick={myFunction}>Click me</button>
    
  • Listener:

    HTML – Bind the listener in the form of the string.
    React – Bind the listener in the form of function name or method name as a variable.

  • Prevent default behavior:

    HTML – You can return `false`.

    <a href="#hash" onclick="console.log("Link clicked!"); return false;">
    </a>
    

React – You must call `preventDefault()` explicitly.

function handleClick(e) {
  e.preventDefault();
  console.log('Link clicked!');
}

5. How to bind methods or event handlers in JSX?

There are five different ways to bind methods or handle events in React.

    • Inline method binding

      <input type="text" onchange={this.inputChange.bind(this)}>
      
    • Bind method in constructor

      constructor(props) {
        super(props);
        this.inputChange = this.inputChange.bind(this);
      }
      
      render() {
        return(
          <input onchange={this.inputChange}>
        );
      }
      
    • Method binding using arrow function

      <input type="text" onchange="{(e)" ==""> this.inputChange(e)}>
      

Refer to this article: Handle Events in React

6. How to pass a parameter to an event handler or callback?

There are two different ways to pass the parameter to an event handler.

  • Bind method parameters

    inputChange(p1, p2, e) {
      console.log('Param1: ', p1);
      console.log('Param2: ', p2);
    }
    
    render() {
      return(
        <input onchange="{this.inputChange.bind(this," 'parameter="" 1',="" 2')}="">
      );
    }
    
  • Binding method with parameters using arrow function

    inputChange(p1, p2, e) {
      console.log('Param1: ', p1);
      console.log('Param2: ', p2);
    }
    
    render() {
      return(
        <input onchange="{(e)" ==""> this.inputChange('Parameter 1', 'Parameter 2', e)}>
      );
    }
    

Refer to this article: Handle Events in React

7. What are synthetic events in React?

The `SyntheticEvent` is a cross-browser wrapper around the browser's native event. It's API is the same as the browser's native event, including `stopPropagation()` and `preventDefault()`, except the events work identically across all browsers.

8. What is event pooling in React?

The Event Pooling means that the SyntheticEvent object would be reused and all properties would be nullified after the event handler has been called.

For Example, the below code would not work because the event object gets reused.

function handleChange(e) {
  setTimeout(() => {
    console.log(e.target.value);
  }, 100);
}

The following code prevents React from resetting its properties, hence would work.

function handleChange(e) {
  e.persist();
  setTimeout(() => {
    console.log(e.target.value);
  }, 100);
}

Note: This page is only relevant for React 16 and earlier. React 17 on the web does not use event pooling.

9. What is "key" prop and what is the benefit of using it in arrays of elements?

A `key` is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.

Most of the time we use ID from our data as a key.

const todoItems = todos.map(todo => <li key={todo.id}>{todo.text}</li>);

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort.

const todoItems = todos.map((todo, index) => <li key={index}>{todo.text}</li>);

Notes:

  • Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
  • If you extract a list item as a separate component then apply keys on the list component instead of li tag.
  • There will be a warning message in the console if the key prop is not present on list items.

10. What are inline conditional expressions?

You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator `&&`.

<h1>Hello!</h1>;
{
  messages.length > 0 && !isLogin ? (
    <h2>You have {messages.length} unread messages.</h2>
  ) : (
    <h2>You don't have unread messages.</h2>
  );
}

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! πŸ™‚