Saturday 20 August 2022

ReactJs Interview Questions Part -3

21.    What are forward refs?

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

const ButtonElement = React.forwardRef((props, ref) => (
  <button ref={ref} className="CustomButton">
    {props.children}
  </button>
));
 
// Create ref to the DOM button:
const ref = React.createRef();
<ButtonElement ref={ref}>{'Forward Ref'}</ButtonElement>

22.   Which is preferred option with in callback refs and findDOMNode()?

It is preferred to use callback refs over findDOMNode() API. Because findDOMNode() prevents certain improvements in React in the future.

The legacy approach of using findDOMNode:

class MyComponent extends Component {
  componentDidMount() {
    findDOMNode(this).scrollIntoView()
  }
 
  render() {
    return <div />
  }
}

The recommended approach is:

class MyComponent extends Component {
  constructor(props){
    super(props);
    this.node = createRef();
  }
  componentDidMount() {
    this.node.current.scrollIntoView();
  }
 
  render() {
    return <div ref={this.node} />
  }
}

23. Why are String Refs legacy?

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like ref={'textInput'}, and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have below issues, and are considered legacy. String refs were removed in React v16.

                                 i.            They force React to keep track of currently executing component. This is problematic because it makes react module stateful, and thus causes weird errors when react module is duplicated in the bundle.

                               ii.            They are not composable — if a library puts a ref on the passed child, the user can't put another ref on it. Callback refs are perfectly composable.

                             iii.            They don't work with static analysis like Flow. Flow can't guess the magic that framework does to make the string ref appear on this.refs, as well as its type (which could be different). Callback refs are friendlier to static analysis.

                             iv.            It doesn't work as most people would expect with the "render callback" pattern (e.g. )

            v.     class MyComponent extends Component {
           vi.       renderRow = (index) => {
         vii.         // This won't work. Ref will get attached to DataTable rather than MyComponent:
        viii.         return <input ref={'input-' + index} />;
           ix.      
            x.         // This would work though! Callback refs are awesome.
           xi.         return <input ref={input => this['input-' + index] = input} />;
         xii.       }
        xiii.      
         xiv.       render() {
           xv.         return <DataTable data={this.props.data} renderRow={this.renderRow} />
         xvi.       }
}

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

25.  How Virtual DOM works?

The Virtual DOM works in three simple steps.

                                i.            Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.



                              ii.            Then the difference between the previous DOM representation and the new one is calculated.



                            iii.            Once the calculations are done, the real DOM will be updated with only the things that have actually changed.



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

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

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

from documentation

Its main goals are:

                                 i.            Ability to split interruptible work in chunks.

                               ii.            Ability to prioritize, rebase and reuse work in progress.

                             iii.            Ability to yield back and forth between parents and children to support layout in React.

                             iv.            Ability to return multiple elements from render().

                               v.            Better support for error boundaries.

29. 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()})
}

30.  What are uncontrolled components?

The Uncontrolled Components are the ones that store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

In the below UserProfile component, the name input is accessed using ref.

class UserProfile extends React.Component {
  constructor(props) {
    super(props)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.input = React.createRef()
  }
 
  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value)
    event.preventDefault()
  }
 
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          {'Name:'}
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

In most cases, it's recommend to use controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

Wednesday 10 August 2022

ReactJs interview Questions Part 2

11.  Why should we not update the state directly?

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

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

//Correct
this.setState({ message: 'Hello World' })

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


12.What is the purpose of callback function as an argument of setState()?

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

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

setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered'))


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

Below are some of the main differences between HTML and React event handling,

                                i.            In HTML, the event name usually represents in lowercase as a convention:

<button onclick='activateLasers()'>

Whereas in React it follows camelCase convention:

<button onClick={activateLasers}>

                              ii.            In HTML, you can return false to prevent default behavior:

<a href='#' onclick='console.log("The link was clicked."); return false;' />

Whereas in React you must call preventDefault() explicitly:

function handleClick(event) {
  event.preventDefault()
  console.log('The link was clicked.')
}

                            iii.            In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer "activateLasers" function in the first point for example)


14.  How to bind methods or event handlers in JSX callbacks?

There are 3 possible ways to achieve this:

                                i.            Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies for React event handlers defined as class methods. Normally we bind them in constructor.

           ii.     class Foo extends Component {
         iii.       constructor(props) {
           iv.         super(props);
            v.         this.handleClick = this.handleClick.bind(this);
           vi.       }
         vii.       handleClick() {
        viii.         console.log('Click happened');
           ix.       }
            x.       render() {
           xi.         return <button onClick={this.handleClick}>Click Me</button>;
         xii.       }
}

                         xiii.            Public class fields syntax: If you don't like to use bind approach then public class fields syntax can be used to correctly bind callbacks.

         xiv.     handleClick = () => {
           xv.       console.log('this is:', this)
}
<button onClick={this.handleClick}>
  {'Click me'}
</button>

                         xvi.            Arrow functions in callbacks: You can use arrow functions directly in the callbacks.

        xvii.     handleClick() {
      xviii.         console.log('Click happened');
         xix.     }
           xx.     render() {
         xxi.         return <button onClick={() => this.handleClick()}>Click Me</button>;
}

Note: If the callback is passed as prop to child components, those components might do an extra re-rendering. In those cases, it is preferred to go with .bind() or public class fields syntax approach considering performance.


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

You can use an arrow function to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />

This is an equivalent to calling .bind:

<button onClick={this.handleClick.bind(this, id)} />

Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function

<button onClick={this.handleClick(id)} />
handleClick = (id) => () => {
    console.log("Hello, your ticket number is", id)
};


16.What are synthetic events in React?

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


17. 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>
}


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

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 often we use ID from our data as 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>
)

Note:

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

                               ii.            If you extract list item as separate component then apply keys on list component instead of li tag.

                             iii.            There will be a warning message in the console if the key prop is not present on list items.


19.    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 a direct access to the DOM element or an instance of a component.


20.    How to create refs?

There are two approaches

                                i.            This is a recently added approach. 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 within constructor.

                               ii.     class MyComponent extends React.Component {
                             iii.       constructor(props) {
                               iv.         super(props)
                                v.         this.myRef = React.createRef()
                               vi.       }
                             vii.       render() {
                            viii.         return <div ref={this.myRef} />
                                   ix.       }
}

                             x.            You can also use ref callbacks approach regardless of React version. For example, the search bar component's input element is accessed as follows,

                           xi.     class SearchBar extends Component {
                         xii.        constructor(props) {
                            xiii.           super(props);
                         xiv.           this.txtSearch = null;
                               xv.           this.state = { term: '' };
                         xvi.           this.setInputSearchRef = e => {
                        xvii.              this.txtSearch = e;
                          xviii.           }
                         xix.        }
                           xx.        onInputChange(event) {
                         xxi.           this.setState({ term: this.txtSearch.value });
                        xxii.        }
                          xxiii.        render() {
                        xxiv.           return (
                         xxv.              <input
                        xxvi.                 value={this.state.term}
                          xxvii.                 onChange={this.onInputChange.bind(this)}
                         xxviii.                 ref={this.setInputSearchRef} />
                        xxix.           );
                             xxx.        }
}

You can also use refs in function components using closures

Note: You can also use inline ref callbacks even though it is not a recommended approach.

Source : https://github.com/sudheerj/reactjs-interview-questions#table-of-contents.