Tag Archives: Reactjs

React vs Angular

Let’s start with Angular 2. It is a JavaScript framework with open source, that is way much better than the first Angular. The main difference is simplification, which means that you won’t find here all those complicated modules and directives that made Angular 1 so complicated and agglomerate. The result was immediate and the performance of the technology increased greatly. Along with that, now the technology supports native app and can render on a server side.

The technology gained its popularity due to the name of its creator (Google), more than that, the framework is very easy to learn.

Yet, just like every tool, this one has its advantages and disadvantages as well. Among the assets we can list:

  • Orientation on the apps with a big amount of interactive client-side code.
  • Good solution for dynamic apps with a single page.
  • Fast development process
  • Needs less code in some classes
  • Advanced testing features
  • Model-View-Controller ballance

Lower we listed the disadvantages of the framework:

  • Relatively slow when it needs to display large amounts of data
  • Not very SEO friendly.

React JS is a library that also has open source and includes JSX compiler. The fundamental contrast of these systems is that React JS is a library to render your views, not a framework.

It became popular because of the Facebook, that backs it up. React JS is a rather SEO friendly technology. And the icing on a case is its high performance and flexibility.

The pros of the technology are:

  • It’s very compatible with SEO principles
  • UI text cases are easy to create
  • You can reuse the components easily
  • Fast with big number of elements
  • Chrome extension simplifies the debugging process

And here goes a spoon of tar in a barrel of honey:

  • Sometimes the code needs to be long
  • You have to process data changes manually
  • It is view oriented

Making decision

Before making decision investigate the licencing issues, that may occur. As we said, both technologies are open source, however there still may be some limitations connected with their usage.

Model-View-Controller pattern, that lets divide data of the project into tree category and modify each separately if it’s needed is an out-of-the-box feature of Angular 2. Which gives a huge advantage in comparison with React JS, that doesn’t have such option.

The other score one for Angular 2 is its ability to display templates writing easily. With this technology you get very clear UI for the data and can get the end result with a really intuitive approach to the UI writing less code.

React JS is more complicated with it. The technology needs special functions to control data display. You have to determine the way data is represented before it’s coded into the DOM.

Data binding is another question. Angular 2 uses two-way data binding. The data is always directed only in one way, so you always know where your data changes. And this system gets really useful when it goes about debugging.

The Performance issues are extremely important when we work with very massive apps. Angular 2 has a watcher for every binding allows to track all the progressions in Dom. One a View gets new updates, the system compares new values with primary meanings. And the problem is that the technology checks not only the meanings that changed but also all of them. This fact as you understand is a bane of Angular’s productivity.

React JS and its virtual DOM doesn’t need to check new data with the whole system. Once a user entered new data, React created a new virtual Dom and compares it with the previous one. And when the library compares and sees the difference between these two versions, the system rebuilds the virtual DOM. The procedure is performed with the server, thusly reducing the load on a browser. And while there are no active users on a site Psychology Articles, React JS performance increases.

Spread the love

React JS Interview Questions

React is a JavaScript library for building user interfaces. It is based on ES6 Script Extension. ES6 is ECMA Script 2015. React provides seamless manipulation and rendering of DOM objects.

We also consider it as a Popular JavaScript framework based on Redux Architecture. React is developed and maintained by Facebook Inc. React was first created by Jordan Walke, a software engineer working for Facebook. Facebook is using React since 2011 and Instagram since 2012.

So it is a necessary skill to have in your stack. You will be considered if you are an expert in React JS.  Here are some important React Js Interview Questions and Answers useful for Javascript Interview.

What is React?

React is an open-source front-end JavaScript library that is used for building user interfaces especially for single-page applications. It is used for handling the view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.  Read more about – What is React JS?

What are the major features of React?

The major features of React are:

  • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering.
  • Follows Unidirectional data flow or data binding.
  • Uses reusable/composable UI components to develop the view.

What is JSX?

JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.

In the example below the text inside the <h1> tag returns as JavaScript function to the render function.

class App extends React.Component {

  render() {

    return(

      <div>

        <h1>{'Welcome to React world!'}</h1>

      </div>

    )

  }

}

What are Pure Components?

React.PureComponent is exactly the same as React. Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. A component, on the other hand, won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

What is the difference between state and props?

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

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

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.

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.

What is React Fiber?

Fiber is the new reconciliation engine or reimplementation of the 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.

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.

What are the 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()})

}

How to create props proxy for the HOC component?

You can add/edit props passed to the component using props proxy pattern like this:

function HOC(WrappedComponent) {

  return class Test extends Component {

    render() {

      const newProps = {

        title: 'New Header',

        footer: false,

        showFeatureX: false,

        showFeatureY: true

      }

      return <WrappedComponent {...this.props} {...newProps} />

    }

  }

}

What is the context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.

const {Provider, Consumer} = React.createContext(defaultValue)

What is a child prop?

Children are a prop (this.prop.children) that allow you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray. A simple usage of children prop looks as below,

 

const MyDiv = React.createClass({

  render: function() {

    return <div>{this.props.children}</div>

  }

})

ReactDOM.render(

  <MyDiv>

    <span>{'Hello'}</span>

    <span>{'World'}</span>

  </MyDiv>,

  node

)

What is reconciliation?

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

How to set a state with a dynamic key name?

If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.

 

handleInputChange(event) {

  this.setState({ [event.target.id]: event.target.value })

}

 

Why does React use className over class attribute?

class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class. Pass a string as the className prop.

render() {

  return <span className={'menu navigation-menu'}>{'Menu'}</span>

}

Why are fragments better than container divs?

  1. Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
  2. Some CSS mechanisms like Flexbox and CSS Grid have special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
  3. The DOM Inspector is less cluttered.

 

What are stateless components?

If the behavior is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid this keyword altogether.

What are the advantages of React?

  1. Increases the application’s performance with Virtual DOM.
  2. JSX makes code easy to read and write.
  3. It renders both on client and server-side (SSR).
  4. Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
  5. Easy to write unit and integration tests with tools such as Jest.

 

What are the limitations of React?

  1. React is just a view library, not a full framework.
  2. There is a learning curve for beginners who are new to web development.
  3. Integrating React into a traditional MVC framework requires some additional configuration.
  4. The code complexity increases with inline templating and JSX.
  5. Too many smaller components leading to over-engineering or boilerplate.

How are error boundaries handled in React v15?

React v15 provided very basic support for error boundaries using the unstable_handleError method. It has been renamed to componentDidCatch in React v16.

What is the purpose of the render method of react-dom?

This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into a container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.

ReactDOM.render(element, container[, callback])

 

If the optional callback is provided, it will be executed after the component is rendered or updated.

How to use innerHTML to React?

The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass an __html object as key and HTML text as value.

In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

function createMarkup() {

  return { __html: 'First &middot; Second' }

}


function MyComponent() {

  return <div dangerouslySetInnerHTML={createMarkup()} />

}

How events are different in React?

Handling events in React elements has some syntactic differences:

  1. React event handlers are named using camelCase, rather than lowercase.
  2. With JSX you pass a function as the event handler, rather than a string.

What will happen if you use setState() in the constructor?

When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get an error like this: Can only update a mounted or mounting component. So we What will happen if you use setState() in the constructor? What will happen if you use setState() in the constructor? need to use this.state to initialize variables inside the constructor.

How do you conditionally render components?

In some cases, you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (

  <div>

    <h2>{name}</h2>

    {address &&

      <p>{address}</p>

    }

  </div>

)

If you need an if-else condition then use a ternary operator.

const MyComponent = ({ name, address }) => (

  <div>

    <h2>{name}</h2>

    {address

      ? <p>{address}</p>

      : <p>{'Address is not available'}</p>

    }

  </div>

)

 

Spread the love

What is React JS?

React is a JavaScript library for building user interfaces. It is based on ES6 Script Extension. ES6 is ECMA Script 2015. React provides seamless manipulation and rendering of DOM objects.

We also consider it as a Popular JavaScript framework based on Redux Architecture. React is developed and maintained by Facebook Inc. React was first created by Jordan Walke, a software engineer working for Facebook. Facebook is using React since 2011 and Instagram since 2012.

It can be used to render UI for any type of device like Mobile, Desktop and tablets. React use JSX syntax to create dynamic HTML DOM objects. In JSX HTML is part of the Javascript code. JSX stands for JavaScript XML.JSX is an XML/HTML like extension to JavaScript.

According to Official reactjs.org:

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

Reactjs Example:

A Simple Example of JSX:

const MyElement = <h1>Hello World!</h1>;

Features of React JS:

There is a number of features that React is Having. Let have a look at them:

#1.Declarative
Declarative views make your code more predictable and easier to debug. It renders and manipulates just the particular and right component when some change in data occurs and not the whole HTML page.

#2.Component-Based
Break the whole Applications in a simple component. Each component is responsible for some particular rendering. This makes easy to maintain and make it modular. Simple component are used to make a complex and enrich UI. Since Component is written using ES6, we can separate state from DOM.

Example of Component :

class HelloWorld extends React.Component {
  render() {
		return (
			<div>
			Hello {this.props.name}
			</div>
		);
	}
}
ReactDOM.render(
	<HelloWorld name="World" />,
	document.getElementById('hello-world')
);


#3.State Less and State Full Components:
React JS allow us to compose stateless and stateful component. Where we can decide to separate our DOM from the state. A simple stateless component can be used in the application to render the data from different states.

#4. Flexible
When it comes to flexibility, React gives freedom to the composer to create components, modules, and logic to make an application to work efficiently.

#5.Extensible
Plugins and components make it Extensible to any level. Users can create any number of Components and plugins as per convenient. It never restricts. We can use external plugins also.

#6.React Native
React has developed native libraries that are compatible with Android, iOS and UDP applications. So we can develop and deploy native applications for these Operating Systems.

#7.One-way data Flow:
In a React Js application, the components are not allowed to modify any property but can pass a call back function to do so. We can pass a set of values to the component to render the HTML with desired properties.

#8. Fast and Seamless Experience
All the above features make React Seamless and Fast. React provide a fast rendering of component because it renders only the right component where data has been changed.

Why We Should Choose React JS?

  • It is simple as an ES6 script.
  • Easy to learn and a huge community over the internet.
  • It has native libraries, so a single technology can work for mobile, and web applications.
  • It has one-way data binding.
  • It contains self- contained components.
  • Exceptional performance.
  • High flexibility, maintainability, and testability.

You have got a clear picture of React JS. What is React JS and what are the main features that let developers move towards it.

Spread the love