React JS Interview Questions

Jul 1, 2021

What is JSX?

JSX is a XML like syntax extension to ECMAScript (JavaScript XML).

const element = <h1>Hello, world!</h1>;

What are the difference between a class component and functional component?

If a component needs state or lifecycle methods use class component otherwise use functional component.

What are Pure components?

React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate, but React.PureComponent implements it with a shallow prop and state comparison.

What is React.memo?

React.memo is a higher order component. If your component renders the same result given the same props, you can wrap it in a call to React.memo for performance boost.

What is the difference between state and props?

props and state are both plain JavaScript objects. props get passed to the component whereas state is managed withing the component.

What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper around the browser’s native event. It’s API is same as the browser’s native event.

What is Virtual DOM?

The Virtual DOM is an in-memory representation of the real DOM. Whenever any underlying data changes, the entire UIR is re-rendered in Virtual DOM representations. Then the difference between the previous DOM representation and new is calculated. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.

What is “React Fiber”?

Fiber is the new reconcillation engine in React 16. Its main goal is to enable incremental rendering of the virtual DOM.

What are Controlled Components?

With a controlled component, the input’s value is always driven by the React state.

What are Uncontrolled Components?

An uncontrolled component keeps the source of truth in the DOM.

What are Higher-Order Components?

A higher-order component is a function that takes a component and returns a new component.

What is ReactDOM?

The react-dom package provides DOM-specific methods that can be used at the top level of the app.

What are Fragments?

Fragments let you group a list of children without adding extra nodes to the DOM.

What is Context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

What are Keys?

Keys help React to identify which items have changed, are added, or are removed. Keys should be given to elements inside the array to give the elements a stable identity.

What are Refs?

Refs provide a way to access DOM nodes or React elements created in the render method.

What is Ref forwarding?

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

What is ReactDOMServer?

The ReactDOMServer object enables you to render components to static markup.

What are Portals?

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

What are the lifecycle methods of React?

Before React 16.3

  • componentWillMount - Is invoked just before mounting occurs. Its called before render().
  • componentDidMount - Is invoked immediately after a component is mounted.
  • componentWillRecieveProps - Is invoked before a mounted component receives new props.
  • shouldComponentUpdate - To let React know if a component’s output is not affected by the current change in state or props.
  • componentWillUpdate - Is invoked just before rendering new props or state are being received.
  • componentDidUpdate - Is invoked immediately after updating occurs.
  • componentWillUnMount - Is invoked immediately before component is unmounted and destroyed.
  • render - Is invoked to render component
  • constructor - Is called before component is mounted.

React 16.3+

  • getDerivedStateFromProps - Is invoked right before calling the render method, both on the initial mount and on subsequent updates.
  • getSnapshotBeforeUpdate - Is invoked right before the most recently rendered output is committed to e.g. the DOM.

What are hooks?

Hooks are a new addition in React 16.8. They let you use state and other features without writing a class.

What are default props?

defaultProps can be defined as a property on the component class itself, to set the default props for the class.

What are PropTypes?

React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special propTypes property.

References

Categories : JS   React

HTTP protocol evolution

Jun 29, 2021

HTTP(Hyper Text Transfer Protocol) is the underlying protocol of World Wide Web (www). Developed by Tim Berners-Lee and his team between 1989-1991.

HTTP has four versions - HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2.0.

HTTP/0.9

HTTP/0.9 request consists of a single line and start with only possible method GET followed by the path to the resource.

GET /mypage.html
# Example from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP
<HTML>
A very simple HTML page
</HTML>

HTTP/1.0

  • Status code sent at the beginning of the response.
  • HTTP headers introduced for both requests and responses.
  • Transmit other documents than plain HTML files.
GET /mypage.html HTTP/1.0
User-Agent: NCSA_Mosaic/2.0 (Windows 3.1)

200 OK
Date: Tue, 15 Nov 1994 08:12:31 GMT
Server: CERN/3.0 libwww/2.17
Content-Type: text/html
<HTML>
A page with an image
    <IMG SRC="/myimage.gif">
</HTML>

GET /myimage.gif HTTP/1.0
User-Agent: NCSA_Mosaic/2.0 (Windows 3.1)

200 OK
Date: Tue, 15 Nov 1994 08:12:31 GMT
Server: CERN/3.0 libwww/2.17
Content-Type: text/gif
(image content)
# Example from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP

HTTP/1.1

First standardized version of HTTP, published in early 1997.

  • Connection can be reused.
  • Pipelining, allow a second request before answer for first one is fully transmitted.
  • Chunked responses.
  • Additional cache control mechanisms.
  • Content negotiation.
  • Host header added.
GET /en-US/docs/Glossary/Simple_header HTTP/1.1
Host: developer.mozilla.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://developer.mozilla.org/en-US/docs/Glossary/Simple_header

200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Wed, 20 Jul 2016 10:55:30 GMT
Etag: "547fa7e369ef56031dd3bff2ace9fc0832eb251a"
Keep-Alive: timeout=5, max=1000
Last-Modified: Tue, 19 Jul 2016 00:59:33 GMT
Server: Apache
Transfer-Encoding: chunked
Vary: Cookie, Accept-Encoding
(content)

# Example from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP

HTTP/2

Google’s SPDY protocol served as the foundations of the HTTP/2 protocol.

  • Its a binary protocol rather than text.
  • Its a multiplexed protocol.
  • It compresess headers, removes duplication and overhead of data transmitted.
  • It allows a server to populate data in a client cache. The adoption rate is rapid, since having a up-to-date server communicating with a recent browser is enought to enable its use.

References

Categories : HTTP   Web

WebSockets

Jun 27, 2021

WebSocket is a technology that allows a client to establish two way communication with the server.

WebSockets allows establishing a persistent connection between the web browser and server, so that both parties can start sending data at any time.

WebSocket allows to build real time communication apps.

On the frontend, example code to establish a connection to a WebSocket enabled server.

const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', function(event) {
    socket.send('Hello Server!');
});

socket.addEventListener('message', function(event) {
    console.log('Message from server', event.data);
});

socket.addEventListener('close', function(event) {
    console.log('The connection has been closed');
});
// Example code from https://stackoverflow.blog/2019/12/18/websockets-for-fun-and-profit/

On the server, example code to open a connection and listen for messages.

const WebSocket = require('ws');
const ws = new WebSocket.Server({ port: 8080});
ws.on('connection', function connection(wsConnection) {
    wsConnection.on('message', function incoming(message) {
        console.log('server recieved : ${message}');
    });

    wsConnection.send('got your message!');
});
// Example code from https://stackoverflow.blog/2019/12/18/websockets-for-fun-and-profit/

References

Categories : HTTP   Web

Difference between DOMContentLoaded vs Load event in web page

Apr 1, 2021

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. DOMContentLoaded typically marks when both the DOM and CSSOM are ready. If there is no parser blocking JavaScript then DOMContentLoaded event will fire immediately after domInteractive. When the browser processes an HTML-document and comes across a <script> tag, it needs to execute before continuing building the DOM. That’s a precaution, as scripts may want to modify DOM, and event document.write into it, so DOMContentLoaded has to wait. Scripts with async attribute, don’t block DOMContentLoaded. Scripts that are generated dynamically with document.createElement('script') and then added to the webpage don’t block DOMContentLoaded event. External style sheeds don’t affect DOM, so DOMContentLoaded does not wait for them. But if we have script after a style, then the script must wait until the stylesheet loads. The reason for this is that script may need style-dependent properties of elements. So as DOMContentLoaded waits for scripts, it now waits for styles before them as well.

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed);
});

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.

window.addEventListener('load', (event) => {
    console.log('page is fully loaded);
});

References

Categories : HTTP   Web

JavaScript async and defer

Feb 19, 2021

The defer and async attributes were introduced to give developers a way to tell the browser which scripts to handle asynchronously. Both of these attributes tell the browser that it may go on parsing the HTML while loading the script in background, and then execute the script after it loads. This way, script downloads don’t block DOM construction and page rendering. So the user can see the page before all scripts have finished loading.

The difference between defer and async is which momemt they start executing the scripts. defer execution starts after parsing is completely finished, but before the DOMContentLoaded event. It guarantees scripts will be executed in the order they appear in the HTML and will not block the parser. async scripts execute at the first opportunity after they finish downloading and before the windows load event. This means it’s possible that async scripts are not executed in the order in which they appear in the HTML. It also means they can interrupt DOM building. async scripts load at a low priorty. They often load after all other scripts, without blocking DOM building.

References

Categories : HTTP   Web   JavaScript