Interview Questions & Answers

react-js

  • React hooks were introduced in the 16.8 version of React.
  • The need to change a functional components to a class component, whenever state management or lifecycle methods were to be used, led to the development of hooks.

  • Function that let us hook into React state and lifecycle features from a functional component.
  • React Hooks cannot be used in class components.

This means that the SyntheticEvent object would be reused and all properties would be nullified after the event handler has been called. For example, earlier this would not work:

  • This would not work because the event object gets reused.
function handlechange(e) {
  setTimeout(() => {
    console.log(e.target.value);
  }, 100);
}
  • Prevents React from resetting its properties, hence would work.
function handlechange(e) {
  setTimeout(() => {
    console.log(e.target.value);
  }, 100);
}

Nothing! e.persist() was used in Event Pooling but with React 17, Event Pooling has been completely removed.

An object this.refs which is found as an instance inside the component can be used to access DOM elements in ReactJs.

  • It is also called as Fat Arrow Function(=>)
  • Allow to bind the context of components properly since auto-binding is not available. by default in ES6.
  • Make easier to work with higher order functions.
  • Without Arrow Function –
render() {
  return(
    <MyInput onChange={this.handleChange.bind(this)} />
  );
}
  • With Arrow Function
render() {
  return(
    <MyInput onChange={ (e) => handleonChange(e) } />
  );
}

 

We should not update the state directly because of the following reasons:

  • If we update it directly, calling the setState() afterward may just replace the update we made.
  • When we directly update the state, it does not change this state immediately.
  • We will lose control of the state across all components.

  • State can be updated using setState()
class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      name: ‘John’ ,
      id: ‘101’
    }
  }
  render()
  {
    setTimeout(()=>{this.setState({name:’Peter’, id:’102′})}, 2000)
    return (
      <div>
        <h1>Hello {this.state.name}</h1>
        <h2>Your Id is {this.state.name}</h2>
      </div>
    );
  }
}
ReactDOM.render(
  <MyComponent/>, document.getElementById(‘content’)
);