Posted on: July 19, 2020 Posted by: India Hires Comments: 0
React js Interview Questions and Answers

React js Interview Questions and Answers for experienced software developer

If you’re an aspiring front end developer and are getting ready for interviews, then this blog is for you. This blog on Top 21 Questions for React Interviews is the perfect guide for you to learn all the concepts necessary to clear an interview with React. But before we continue with the questions of the reaction interview, let’s take a quick look at the demand and status of React on the market.

The JavaScript tools are slowly and steadily firming their roots on the marketplace and the demand for React certification is exponentially increasing. It is becoming increasingly difficult to choose the appropriate technologies to create an application or website. React is considered by others to be the fastest-growing Javascript framework.

Creating React Components the ES5

          	
	
	var Comments = React.createClass({
	    displayName: 'Comments',

	    getInitialState: function(){
	        return {comments: []}
	    },

	    getDefaultProps: function(){
	        return {some_object: {a:1, b:2, c:3}}
	    },

	    _handleClick: function(){
	        alert('hello world!')
	    },

	    render: function(){
	        return <div>
	            There are {this.state.comments.length} comments
	            <button onClick={this._handleClick}>click me!</button>
	        </div>
	    }
	})

This Comments Component can now be rendered either within another React Object, or directly in ReactDOM.render() call

ReactDOM.render(, document.querySelector(‘.app’))

ES5 Components have certain unique qualities which we will note

  1. Just like the example above, create the getInitialState() function on the Component to set the state to an initial value. When made, what it returns will be the initial state of a Variable.
  2. Alternatively, with the getDefaultProps() method on the ES5 version you can set the default props for the item having a certain value.
  3. The displayName is used with React to test and record errors. If you use JSX, the displayName will be filled out automatically.
  4. For some, denoting a custom method added to a React Component by prefixing it with an underscore, hence handleClick is common practice. handleClick shall be passed as the onClick callback button in the above code. In React’s ES6 API we can’t do this so easily, because the ES5 version has autobinding, but the ES6 does not. Let’s take a look at what delivers autobinding:
Auto-binding

Consider the following example

          	
	
		var indiaData = {
		    name: 'India Hires',
		    speak: function(){ console.log(this.name) }
		}

		window.addEventListener('keyup', indiaData.speak)
	

Invoking indiaData.speak() will log “India Hires” in the console, but pressing a key will log undefined, as the callback context is the global entity. The global object of the user-window-is this inside the indiaData() function, so that this.name is the undefined window.name, which is undefined

React in ES5 automatically does autobinding, effectively doing the following:
          	
	
		window.addEventListener('keyup', indiaData.speak.bind(indiaData));
	

Autobinding automatically binds our functions to the instance of the React Component so that the render() smoothly works by passing the function by reference. The ES6 way of creating react components works a little differently and favors the ES6 class … Spreads out … Syntax, and no autobonding function:

	
	class Comments extends React.Component {
	    constructor(props){
	        super(props)
	        this.state = {comments: []}
	    }

	    _handleClick(){
	        alert('hello world!')
	    }

	    render(){
	        return <div>
	            There are {this.state.comments.length} comments
	            <button onClick={() => this._handleClick}>click me!</button>
	        </div>
	    }
	}
	Comments.defaultProps = {a:1, b:2, c:3}
	Comments.displayName = 'Comments'
	

Notice that in ES6, we have a constructor() that we use to set the initial state, We can add default props and a display name as properties of the new class created, and The render() method, which works as normal, but we’ve had to alter how we pass in the callback function. This current approach (<button onClick={() => this._handleClick}>click me!</button>) will create a new function each time the component is re-rendered; so if it becomes a performance bottleneck, you can always bind manually and store the callback:

	
	class Comments extends React.Component {
		constructor(...args) {
			super(...args);
			this.state = { toggledOn: false };
			this._handleClick = this._handleClick.bind(this);
		}

		_handleClick() {
			this.setState(prevState => ({ toggledOn: !prevState.toggledOn });
		}

		render() {
			return <button onClick={this._handleClick}> { this.state.toggledOn ? 'ON' : 'OFF' } </button>
		}
	}
	

React uses Virtual DOM to update the real DOM which makes it efficient and faster. The browser follows the HTML instructions to construct the Document Object Model or DOM. All the elements in the HTML document become DOM elements when the browser loads HTML and renders the user interface.

DOM is a hierarchy of elements starting with the root element.

How Does Virtual DOM Works

Virtual DOM is nothing but the javascript object representation of real DOM. Updating javascript objects is easier and faster when compared with updating the real DOM.

How Does Virtual DOM Works

Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.

  • Mounting – Birth of your component
  • Update – Growth of your component
  • Unmount – Death of your component

Common React Lifecycle Methods

Render()

The render() method is the most used lifecycle method. This is the only required method within a class component in React. it handles the rendering of your component to the UI. It happens during the mounting and updating of your component.

  	
		class Hello extends Component{
		   render(){
		      return <div>Hello {this.props.name}</div>
		   }
		}
	

Render method is a pure function and pure functions always return the same output when the same inputs are passed. This means that we can not setState() within the render();

Mounting

Constructor

The first thing that gets called is our component constructor if our component is a class component. The constructor gets called with the component props. We must call super and pass in the props. We can then initialize our state, setting the default values and use the constructor for function binding as well.

  	
		class MyComponent extends Component {
		  constructor(props) {
		    super(props);
		    this.state = {
		      counter: props.initialCounterValue,
		    };
		  }
		}

	

Note that using a constructor is optional, and you can initialize your state like so if your Babel setup has support for class fields:

getDerivedStateFromProps()

When mounting, getDerivedStateFromProps is the last method called before rendering. We can use it to set state according to the initial props. This will be a safer alternative to the componentWillReceiveProps() method. It is called just before calling the render() method. This is a static function that does not have access to “this“. This method returns an object to update state in response to prop changes. It can return a null if there is no change to state.

  	
		static getDerivedStateFromProps(props, state) {
		    if (props.currentRow !== state.lastRow) {
		      return {
		        isScrollingDown: props.currentRow > state.lastRow,
		        lastRow: props.currentRow,
		      };
		    }
		    // Return null to indicate no change to state.
		    return null;
		  }
	

Note that we could have placed this code in the constructor. The advantage of getDerivedStateFromProps is that it is only meant for setting state, whereas a constructor has multiple uses. getDerivedStateFromProps is also called both before mount and before updating, as we’ll see in a bit.

componentDidMount()

componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls, if you need to load data from a remote endpoint. Calling the setState() here will update state and cause another rendering but it will happen before the browser updates the UI. This is to ensure that the user will not see any UI updates with the double rendering.

  	
		componentDidMount() {
		    this.bricks = initializeGrid(this.grid.current);
		    layoutInitialGrid(this.bricks)
		    this.interval = setInterval(() => {
		      this.addBlocks();
		    }, 2000);
		  }

	

Updating

getDerivedStateFromProps()

If we need to update our state based on a prop changing, we can do it here by returning a new state object. Here’s some examples:

  1. Resetting a video or audio element when the source changes
  2. Refreshing a UI element with updates from the server
  3. closing an accordion element when the contents change
  	
		static getDerivedStateFromProps(props, state) {
		  if (state.blocks.length > 0) {
		    return {};
		  }
		  return { blocks: createBlocks(props.numberOfBlocks) };
		}
	

(One last point about static methods like getDerivedStateFromProps: We don’t have access to the component via this. So we couldn’t access our grid ref, for example.)

shouldComponentUpdate()

This lifecycle method is called whenever there is an update to the props or state and it returns a boolean value true by default. We can return false if you don’t want to re render the DOM for this change. This is really useful to improve the performance of the app. Anytime setState() is called, the component re-renders by default.

  	
		shouldComponentUpdate(nextProps, nextState) {
		 return this.props.title !== nextProps.title || 
		  this.state.input !== nextState.input 
		}
	
getSnapshotBeforeUpdate()

This will be a safer alternative to the previous lifecycle method componentWillUpdate(). It is called right before the DOM is updated. The value that is returned from getSnapshotBeforeUpdate() is passed on to componentDidUpdate().

  	
		getSnapshotBeforeUpdate(prevProps, prevState) {  
		  if (prevState.blocks.length < this.state.blocks.length) {
		      const grid = this.grid.current;
		      const isAtBottomOfGrid =
		        window.innerHeight + window.pageYOffset === grid.scrollHeight;
		      return { isAtBottomOfGrid };
		    }
		    return null;
		  }
	

Most Common Use Case: Taking a look at some attribute of the current DOM, and passing that value on to componentDidUpdate.

componentDidUpdate()

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop

  	
		componentDidUpdate(prevProps) {
			 //Typical usage, don't forget to compare the props
			 if (this.props.userName !== prevProps.userName) {
			   this.fetchData(this.props.userName);
			 }
		  }
	

Unmounting

componentWillUnmount()

This is invoked just before the component is unmounted and destroyed. We cannot modify the component state in componentWillUnmount lifecycle. This component will never be re-rendered and because of that we cannot call setState() during this lifecycle method.

  	
		componentWillUnmount() {
		 window.removeEventListener('resize', this.resizeListener)
		}
	

Errors

getDerivedStateFromError()

This lifecycle method is used in ErrorBoundary class. Actually, any class becomes ErrorBoundary if it uses this lifecycle method. This is used to render the fallback UI if something goes wrong in the component tree instead of displaying some weird errors on the screen.

  	
		static getDerivedStateFromError(error) {
		  return { hasError: true };
		}
	
componentDidCatch()

This lifecycle method is used in ErrorBoundary class. Actually, any class becomes ErrorBoundary if it uses this lifecycle method. This is used to log the errors if something goes wrong in the component tree.

  	
		componentDidCatch(error, info) {
		  sendErrorLog(error, info);
		}
	

Note that componentDidCatch only works for errors in the render/lifecycle methods. If our app throws an error in a click handler, it will not be caught.

  	
		class ErrorBoundary extends Component {
		  state = { errorMessage: null };
		  static getDerivedStateFromError(error) {
		    return { errorMessage: error.message };
		  }
		  componentDidCatch(error, info) {
		    console.log(error, info);
		  }
		  render() {
		    if (this.state.errorMessage) {
		      return <p>Oops! {this.state.errorMessage}</p>;
		    }
		    return this.props.children;
		  }
		}
	

Other lifecycle methods

componentWillMount()

This lifecycle method is called, as the component enters the DOM and we have the last chance to edit the state so that it will be displayed on the screen. It occurs only once.

componentWillReceiveProps()

Whenever there is a change in the props, the component enters into the update phase. This lifecycle method is called to receive the props and we can check the previous props and current props here and we can update the state depending on the result.

componentWillUpdate()

Whenever there is a change in the props or state, this lifecycle method is called. We can have a chance to access the state and edit it before rendering the UI.

component Lifecycle Methods

TCS Possible Technical Interview Questions and Answers

The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events. Props (short for properties) are a Component’s configuration. Props are how components talk to each other. They are received from above component and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data — callback functions may be passed in as props.

There is also the case that we can have default props so that props are set even if a parent component doesn’t pass props down.

	          	
		class Search extends Component{
			constructor(props){
				super(props);
				this.state = { term: ''}
			}
		   	render(){
		   		return(
			   		<div>
			   			<input value={this.state.term} onChange={e => this.onInput(e.target.value)} />
			   		</div>
		   		);
		   	}

		   	onInput(search){
		   		this.setState({search});
		   		this.props.onSearchTermChange(search);
			}
		}
	

Props and State do similar things but are used in different ways. The majority of our components will probably be stateless. Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed. The state is used for mutable data or data that will change. This is particularly useful for user input.

Higher order components are the components which take a component as an argument and produces another component. Array.map, Array.filter and Array.reduce are the higher order functions

Exp:
	
		const numbers = [10,20,40,50,60,70,80];
		const out1 = numbers.map(num => num * 100);
		console.log(out1);

		const isPassed = marks=> marks > 80; // function
		const message = msg => "The student  is "+ msg; // function
		function isStudentPassed(marks, isPassed, message) {
		    const returnMessage = isPassed(marks)?message("passed"):message("failed");
		    return returnMessage;
		}
		// passing functions as an arguments
		console.log(isStudentPassed(85, isPassed , message))
		// The student is passed
	
Exp:
  	
		DOM.render(
	    <LazyLoad>
	        <img src="https://media.giphy.com/media/HhvUpQhBWMtwc/200.gif"/>
	        <img src="https://media2.giphy.com/media/3oEduUDvycvu3GYkdG/200w.gif"/>
	        <img src="https://media0.giphy.com/media/142UITjG5GjIRi/200w.gif" />
	    </LazyLoad>, document.body)
	
Creating an HOC means handling this.props.children in the Component’s code:
  	
		class LazyLoad extends Component {
		    constructor(p){
		        super(p)
		        this.state = { loaded:0 }
		        this._scroll = this._scroll.bind(this)
		    }
		    _scroll(){
		        let el = DOM.findDOMNode(this)
		        let {top} = el.getBoundingClientRect()
		        let viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
		        if(top < (viewportHeight + this.props.top)) {
		            window.removeEventListener('scroll', this._scroll)
		            this.setState({loaded:1})
		        }
		    }
		    componentDidMount(){
		        window.addEventListener('scroll', this._trackYPosition)
		        this._scroll()
		    }
		    componentWillUnmount(){
		        window.removeEventListener('scroll', this._trackYPosition)
		    }
		    render(){
		        let {children} = this.props,
		            {loaded} = this.state
		        return <div> {loaded && children} </div>
		    }
		}

		LazyLoad.defaultProps = {
		    top: 100
		}

	
	
		const hoc = (WrappedComponent) => (props) => {
		  return (
		    <div>
		      <WrappedComponent {...props}>
		        {props.children.toUpperCase()}
		      </WrappedComponent>
		    </div>
		  )
		}

		const Username = (props) => (
		  <div>{props.children}</div>
		)

		const UpperCaseUsername = hoc(Username)

		const App = () => (
		  <div>
		    <UpperCaseUsername>Kingsley</UpperCaseUsername>
		  </div>
		);
	

Of your application, lists are an important feature. Growing application is expected to use the lists in every way. A list of tasks like a calendar app, a list of pictures like Instagram, a list of shopping cart items, and much more could be available. There are numerous case applications. Lists can be heavy performance in an application. Imagine an app with an enormous list of videos or photos and scroll thousands more. The performance of the app could take a toll.

As performance is an important aspect, it is necessary to ensure the optimal performance when using lists.

Do you know that in React, each list element needs a unique key while using lists? Let's learn more about React 's lists and keys, and how to implement it in the correct way.

Exp:
	
		class List extends Component {
		    constructor(p){
		        super(p)
		        this.state = {
		            items: Array(5).fill(1).map((x,i) => ({id:i}))
		        }
		    }

		    componentDidMount(){
		        const random = (a,b) => Math.random() < .5 ? -1 : 1

		        setInterval(() => {
		            this.setState({
		                items: this.state.items.sort(random)
		            })
		        }, 20)
		    }

		    render() {
		        let {items} = this.state
		        return <ul>
		            	{items.map(item => <li key={item.id}>{item.id}</li>)}
		        </ul>
		    }
		}
		DOM.render(<List />, document.body)
	

The setInterval() occurring on mount reorders the items array in this.state every 20ms. Computationally, if React is reordering the items in the state, then it would manipulate the DOM elements themselves instead of “dragging” them around between positions in the <ul>.

It is worth noting here that if you render a homogenous array of children – such as the <li>'s above – React will actually console.warn() you of the potential issue, giving you a stack trace and line number to debug from. You won’t have to worry about React quietly breaking.

Can I just use indexes as keys? — Only under some exceptions

Using Index as a key is an anti-pattern. You may wonder, why don’t we just use indexes as keys when looping through an array. Although, many developers have done that in their code it is not necessarily ideal. React recommends that you do not use indexes as keys since it could impact performance negatively and could lead to some unstable component behavior.

Exp:
	
		const todoItems = todos.map((todo, index) =>
		  // Only do this if items have no stable IDs
		  <li key={index}>
		    {todo.text}
		  </li>
		);
	

In the above example you can see that we loop through the todos and assign the index of each item as the key. For some use cases which we will see below, this is acceptable. Reordering a list, or adding and removing items from a list, when indexes are used as keys can cause problems with the component state. If the key is an index it changes to reorder an item. The component state can, therefore, be mixed up and the old key can be used for a different instance of the component.

Hence avoid this practice, and ensure that unique ids are created to be assigned as the key. There are some situations when it might be acceptable to assign the index as a key.

What are some exceptions where use of index as key is safe?
  1. If your list is static and will not change.
  2. The list will never be re-ordered.
  3. The list will not be filtered (adding/removing items from the list).
  4. There are no ids for the items in the list.

Note: Using index as a key can lead to potential unexpected behaviour within the component.

Keys must be Special, but only among their siblings

It's useful to keep in mind that although a key needs to be unique for each item, this rule applies only within an array. In other words, every item within an array needs to have a unique key, but it doesn't need to be unique globally. The same key may be used for a variety of other unrelated components and lists.

Keys are not automatically passed onto the component as a prop

In the example below, you can see that I specifically transfer the item.id which is the key to the component as another prop I d). This is because React doesn't pass the key automatically like a prop. If you wanted to use the key for some computation, you 'd have to pass it as another prop as we did in this instance.

Refs is a feature that React provides to access the DOM element and the reaction element that you might have generated on your own. They are used in cases where we want to adjust a child's component value, without using props and all. They also offer us good flexibility, since with them we can use callbacks.

Exp:
	
		// using refs 
		class App extends React.Component { 
		 constructor(){ 
		  super(); 
		  this.state = { sayings: ""}; 
		 } 
		 update(e){ 
		  this.setState({ sayings: this.refs.anything.value}); 
		 } 
		 render(){ 
		  return ( 
		   <div>
		   		India Hires Says:- <input type="text" ref="anything" onChange = {this.update.bind(this)}/> 
			   	<p>					   
				   <em>{this.state.sayings}</em> 
				</p>
			</div> 
		  ); 
		 } 
		} 
		 ReactDOM.render(< App />, document.getElementById('root'));
	

In the above we make use of refs provided by React, they can also be used to add callback functions inside them which is helpful in many cases.

When to use refs
  1. Helpful when using third party libraries.
  2. Helpful in animations.
When not to use refs
  1. Should not be used with functional components because they dont have instances.
  2. Not to be used on things that can be done declaritvely.

Functional components are very useful in React, especially when you want to isolate state management from the component. That’s why they are often called stateless components.

However, functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since they are not classes by definition.

In fact, if you have a functional component and you want React to treat it as a pure component, you will have to convert the functional component to a class component that extends React.PureComponent.

Here is a simple example:
	
		// FUNCTIONAL COMPONENT
		function Percentage({ label, score = 0, total = Math.max(1, score) }) {
		  return (
		    <div>
		      <h6>{ label }</h6>
		      <span>{ Math.round(score / total * 100) }%</span>
		    </div>
		  )
		}					
	
	
		// CONVERTED TO PURE COMPONENT
		class Percentage extends React.PureComponent {

		  render() {
		    const { label, score = 0, total = Math.max(1, score) } = this.props;

		    return (
		      <div>
		        <h6>{ label }</h6>
		        <span>{ Math.round(score / total * 100) }%</span>
		      </div>
		    )
		  }

		}
	

PropTypes provides type checking for your components and serves as nice documentation to the other developers. We can also define the Default Props for each component to display if the component doesn’t receive any props

Here is a simple example:
	          	
	import React, {Fragment} from 'react';
	import PropTypes from 'prop-types';
	export const UserDisplay = ({name, address, age}) => {
		UserDisplay.defaultProps = {
		    name: 'myname',
		    age: 100,
		    address: "0000 onestreet"
		};
		return (
		    <Fragment>
		    <div>
		        <div class="label">Name:</div>
		        <div>{name}</div>
		    </div>
		    <div>
		        <div class="label">Address:</div>
		        <div>{address}</div>
		    </div>
		    <div>
		        <div class="label">Age:</div>
		        <div>{age}</div>
		    </div>
		</Fragment>

		)
	}
	UserDisplay.propTypes = {
		name: PropTypes.string.isRequired,
		address: PropTypes.objectOf(PropTypes.string),
		age: PropTypes.number.isRequired
	}
	UserDisplay.propTypes = {
		counts: PropTypes.array,
		users: PropTypes.arrayOf(PropTypes.object),
		alarmColor: PropTypes.oneOf(['red', 'blue']),
		description: PropTypes.oneOfType([
			PropTypes.string,
			PropTypes.instanceOf(Title)
		]),
		userWithName: (props, propName, componentName) => { // Custom type
		    if (!props[propName] || !props[propName].name) {
		    	return new Error( "Invalid " + propName + ": No name property defined for component " + componentName)
		    }
		}
	}					
				
			

PropTypes can be used to test Props for value of any kind. Here are a few fast type checkers which React has built-in types for JavaScript:

  • React.PropTypes.array,
  • React.PropTypes.bool,
  • React.PropTypes.func,
  • React.PropTypes.number,
  • React.PropTypes.object,
  • React.PropTypes.string,
  • React.PropTypes.symbol,

We can also test that props are React and DOM types:

  • React.PropTypes.node,
  • React.PropTypes.element,

And we have the ability to test more complex types, such as "shapes", "instances of", or "collections of":

  • React.PropTypes.instanceOf(Message),
  • React.PropTypes.oneOf(['News', 'Photos']),
  • React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.instanceOf(Message)])
  • React.PropTypes.arrayOf(React.PropTypes.number),
  • React.PropTypes.shape({ color: React.PropTypes.string, fontSize: React.PropTypes.number })

Using these PropTypes to make errors, and track bugs. PropTypes should prevent the team from wasting too much time during the debugging and documentation process when used efficiently, ensuring tighter standards and understanding of the can component library.

In designing a React application, a deeply nested component is often needed to use data generated by another component that is much higher in the hierarchy.

Consider the following example components:

  • <EditUsersPage />, which includes selectedUserAddress in its component state and renders a <User /> component
  • <User />, which renders a <UserDetails /> component
  • <UserDetails />, which renders a <UserAddress /> component
  • A <UserAddress /> component that requires the selectedUserAddress property stored in the <EditUsersPage /> state

The easiest solution is to simply move from the source component to the deeply nested component a selectedUserAddress prop from each component into the next in the hierarchy. It is called drilling with prop.

The main disadvantage of prop drilling is that components which otherwise should not be aware of the data — in this case < User/ > and < UserDetails/ > — become unnecessarily complicated and more difficult to maintain.

A common solution is to use the React context to prevent prop-drilling. It allows for the creation of a Provider component that provides data, and allows nested components to consume context data through either a User component or a useContext button.

Although context can be used directly for sharing global state, context can also be used indirectly through a module for state management, such as Redux.

React's StrictMode is sort of a helper component that will help you write better react components, you can wrap a set of components with and it'll basically:

  1. Verify that the inside components meet any of the required procedures, and alert you if not in the console.
  2. Verify that the deprecated methods are not being used, and you will be warned in the console if they are used strict mode.
  3. Support you prevent such side-effects by identifying possible threats.

Strict mode is growth-driven and you don't have to think about it impacting your production construction.

I find it especially useful when I work on new codebases to enforce strict mode because I want to see what kind of code/components I'm facing. Even if you're on bug hunting mode, sometimes it's a good idea to cover the components/blocks of code you think could be the root of the issue with < StrictMode/ >.

So hey, you 're on the right direction to understand the strict mode, keep it up, I guess it's one of those things that you should understand when playing with them, so go ahead and have some fun.

When it comes to React vs Angular, just take a quick look at their website and you'll know the most basic yet crucial difference between React, the JS library and Angular, the front-end development framework.

Here's what you 're going to find:

Angular: a framework. Mobile & Desktop

React: A JavaScript library to build user interfaces

This basic conceptual difference in development is based on React vs Angular comparison to the next level. It is true that comparing a framework with a library is not fair in itself. However, a comparison is worthwhile and essential to understanding how the differences between React and Angular have an impact on the web or mobile app development process.

Here we have created this React vs Angular Comparison Guide which will help you choose between React and Angular as well as Angular native app development company or React app development company.

Angular Vs React Architectural Difference
Angular:

This is a robust front-end development framework that allows you to structure your application. You start coding your application without worrying about the routing of libraries. Angular JS, as a front-end development framework, provides various advanced functionalities to Angular developers, such as:

  1. Templates for building UI views with a strong template syntax
  2. Command line tools to add and test components
  3. Intelligent code completion IDEs
  4. Protractor to make the test run quicker and easier
  5. Intuitive APIs for complex choreography and animation timelines
  6. ARIA enabled components and built-in test infrastructure
  7. Injection of Dependency
  8. Protection of XSS
React:

It is an open-source JavaScript library, which is also called V (View) in the MVC framework, and the React developer must consider M (Model) and C (Controller). Views are logical-less files that are controlled by the controllers. So, the big question is, if the framework already has a view, then why do we need React? This is because React does not remove views but applies them to interchangeable UI components such as tab bars, pop up modals, sortable modals, lists, and comment boxes.

Some of the key functionality of React JS are

  1. JSX, JavaScript syntax extension
  2. Easy-to-create reaction elements
  3. Respond to the DOM to change the DOM and suit the Respond elements
  4. Component API to break the UI into separate, reusable sections
  5. Protection of XSS

Now that we know the main strengths of Angular and React, let 's dive deeper into the details that classify the features and functions that add power to Angular vs React debate.

Type Angular React

Type

Framework

Frontend Library

Data Binding

Two-way Binding

One-way Binding

DOM

Real

Virtual

Template

HTML+Typescript

JavaScript + JSX

Application logic

Services

Flux/Redux

Mobile Development

Ionic framework

Native UI experience

Abstraction

Strong

Medium

Technology

Complete MVC framework written in javascript

View in MVC, requires flux to implement architecture

According to the State of Javascript Survey 2019, we find React as one of the top choices of Javascript Framework and received the overwhelmed response from developers.

Front-end frameworks and libraries
React vs. Angular: Choosing one of two robust options

JavaScript frameworks and libraries are very popular for web app development, and both React and Angular are very popular. We explained their differences and advantages, and we also outlined the factors that should be considered before selecting the correct JavaScript framework/library.

You need to weigh between React and Angular on the basis of your specific project requirements. For example, if you are running a large project, you will benefit more from using React since its one-way data-binding provides a better overview of the data. On the other hand, because of its two-way data-binding, you will find Angular to be a better approach in a smaller project.

When to Use React?

Not every smartphone or web application development project needs React. This is used along with a flow patterned library, such as Mobx and Redux. Below are the cases where you can use React to create web applications:

  1. When your project has several components in a changing state, such as dynamic inputs, extended / collapsed accordion parts, access permissions, and more.
  2. Complex applications where change is common. It helps to fight the spaghetti code, where the organization and structure of the code do not match.
  3. When managing DOM operations, it is tough
  4. If you desperately need to complete the project, it has modular components that save a lot of developers' time.
  5. You have a small team of HTML, CSS , and JavaScript experts.
When to Use Angular?

Angular has released a range of versions since AngularJS was introduced. It has advanced features, including the use of nglf with "other," strong animations, and support for Angular CLI. Below are the cases where you can use Angular for your project:

  1. When you need a good navigation service. DOM shadowing and maintenance of data using services
  2. Full configuration of the server is needed
  3. Maintain styling with encapsulation style and part
  4. Building progressive web applications (PWAs)
  5. Want to create a large-scale, feature-rich application

Angular is an excellent choice for the development of enterprise applications. Angular development companies are widely used to create web applications for large enterprises.

Using a Class Component

The componentDidMount() lifecycle hook can be used with class components:

	
		class Home extends Component {
		  componentDidMount() {
		    trackPageView('Homepage');
		  }
		  render() {
		    return <div>Homepage</div>;
		  }
		}		
	

Any actions specified within the componentDidMount() lifecycle hook will be called only once the component is first installed.

Using a Function Component

The useEffect() hook can be used with function components:

	
		const Homepage = () => {
		  useEffect(() => {
		    trackPageView('Homep');
		  }, []);
		  
		  return <div>Homepage</div>;
		};
	

The useEffect() hook is more flexible than the life-cycle methods used for class components. It has two parameters:

  1. The first parameter to be used is the callback function to be executed.
  2. The optional second parameter to be used is an array containing any variables to be monitored.

When the callback is executed, the value passed as the second argument controls:

  1. If the second parameter is not defined, the callback is executed every time the component is rendered.
  2. If the second parameter contains an array of variables, the callback will be executed as part of the first render cycle and will be executed again every time an item in the array is modified.
  3. If the second parameter contains an empty array, the callback will be executed only once as part of the first rendering cycle. The example above shows how passing an empty array can result in a similar behavior to the componentDidMount() hook within the function component.

Method #1: Inline styling of React components

We can add inline styles to any React component that we want to render. These styles are written as attributes and passed to the element. Let's use inline styles to style parts of our component:

	
		class Home extends Component {
		  render() {
		    return <div style={{ backgroundColor: "#44014C", width: "300px", minHeight: "200px"}}>
				        <h2 style={{ padding: "10px 20px", textAlign: "center", color: "white"}}>ToDo</h2>
				    </div>
		  }
		}		
	
Creating a style object variable

We create a variable style object in the same way that we create a JavaScript object. This object is then passed to the style attribute of the element that we want to style. So instead of adding the inline styles directly, as we did in the previous example, we 're just passing the variables of the object:

	
		const TodoComponent = {
		  width: "300px",
		  margin: "30px auto",
		  backgroundColor: "#44014C"
		}
		const Header = {
		  padding: "10px 20px",
		  color: "white"
		}
		class Home extends Component {
		  render() {
		    return <div style={TodoComponent}>
				        <h2 style={Header}>ToDo</h2>
				    </div>
		  }
		}		
	

Note: The camelCase to dash-separated string change applies only to the property names and not property values.

Sharing styles across many React components
	
		const Header = {
		  padding: "10px 20px",
		  textAlign: "center"
		}

		const ErrorMessage = {
		  color: "white",
		  fontSize: "13px"
		}

		const styles = {
		  Header: Header,
		  ErrorMessage: ErrorMessage
		}
	

Method #2: CSS-in-JS Modules Such as Styled Components, Emotion, and Styled-jsx

With Styled Components, we can write the actual CSS in our JavaScript file. This means that you can use all the features of the CSS — like media queries, pseudo-selectors, nesting, etc.—in JavaScript.

Using styled-components, we can create reusable style components. It's pretty exciting to create and use. Explaining with an example here is going to do us a lot of good.

First, we need to install it, so run the following in the directory of your React app:

$ npm install --save styled-components

	
		import styled from 'styled-components';

		const TodoComponent = styled.div`
				background-color: #44014C;
				width: 300px;`;

		class Home extends Component {
		  render() {
		    return (
		    	<TodoComponent>
		    		<h2 style={Header}>ToDo</h2>
		    	</TodoComponent>
		    )
		  }
		}

	

In the code above, we used the styled component that we created — TodoComponent — on line 5 like any other HTML element. The only difference is that it comes with predefined styles of its own.

Method #3: CSS Modules, Pre-processors Such as Sass, Stylus, and Less

The CSS module is basically a.css file that is being compiled. When compiled, two outputs are generated. One is the CSS that is a modified version of the CSS input with a renamed class name. The other is a JavaScript object that maps the original name of the CSS with a renamed name.

	
		import styles from './styles.css';
		class Message extends Component {
		    render() {
		        return (
					I am an error message
				) 
			} 
		}
	

If a performance issue such as slow rendering is found inside an app, the primary move is to use the Profiler tool provided with the Google Chrome and Mozilla Firefox React Developer Tools software plugin. The Profiler tool helps developers to find components which take longer than necessary for rendering or rendering.

One of the most popular problems in React applications is the unnecessary render of components. React offers two methods that are useful in these situations:

  1. React.memo(): This prevents unnecessary re-rendering of function components
  2. PureComponent: This prevents unnecessary re-rendering of class components

Both tools depend on a shallow comparison of the component props – if the props are not changed, the component will not return. The shallow comparison, although both tools are very useful, offers an additional performance burden so that they can have a negative impact if they are used incorrectly. The reaction profiler allows you to measure your performance before and after using these tools to ensure that your performance is actually improved by changing it.

useState()

	
		const [count, setCounter] = useState(0);
		const [moreStuff, setMoreStuff] = useState(...);

		const setCount = () => {
		    setCounter(count + 1);
		    setMoreStuff(...);
		};
	

UseState is one of the built-in reactive hooks. UseState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the state of the counter.

We can use the setCounter method to update count status anywhere-in this case we use it within the setCount function where we can do more; the idea with hooks is that we can keep our code more functional and avoid class-based components if not desired / needed.

useEffect()

React useEffect is a function that is executed for three different React component lifecycles.These lifecycles are componentDidMount, componentDidUpdate, and componentWillUnmount lifecycles.

	
		import React, { useState, useEffect } from 'react';

		const App = () => {
		  const [message, setMessage] = useState('Hi there, how are you?');

		  useEffect(() => {
		    console.log('trigger use effect hook');

		    setTimeout(() => {
		      setMessage("I'm fine, thanks for asking.");
		    }, 1000)
		  }, [])
		  return <h1>{message}</h1>
		};
		export default App;
	

UseEffect accepts a function as the first argument. This function handler will take care of any side effects you like when it's running. The function is a callback function after one of the lifecycle components has been triggered.

Using Async and Await in React useEffect

React.useEffect does NOT allow you to add async in the callback function

	
		// This will cause your React application to break!
		React.useEffect(async() => {
		  // ... stuff
		}, []);
	

React is expecting a regular function and not a promise. But if you’d like to use async/await you can move your code into its own function, and invoke it inside React.useEffect().

	
		async function fetchData() {
		  try {
		    const response = await fetch('url/data/api');
		    const { data } = await response.json();
		    console.log(data) // [ { name: 'Mr. Whiskers' }, ...data ]
		  } catch(e) {
		    console.error(e);
		  }
		}

		React.useEffect(() => {
		  fetchData();
		}, []);
	

Controlled Component

The controlled component is bound to a value and its changes will be handled in code using event-based callbacks. Here, the input form element is handled by the response itself rather than by the DOM. In this case, the mutable state is kept in the state property and will be updated only with the setState() method.

Controlled components have functions that govern the transmission of data to each event that occurs onChange. This data is then saved to state and updated using the setState) (method. It makes the component have better control over the elements of the form and the data.

	
		class NameForm extends React.Component {
		  constructor(props) {
		    super(props);
		    this.state = {value: ''};

		    this.handleChange = this.handleChange.bind(this);
		    this.handleSubmit = this.handleSubmit.bind(this);
		  }

		  handleChange(event) {
		    this.setState({value: event.target.value});
		  }

		  handleSubmit(event) {
		    alert('A name was submitted: ' + this.state.value);
		    event.preventDefault();
		  }

		  render() {
		    return (
		      <form onSubmit={this.handleSubmit}>
		        <label>
		          Name:
		          <input type="text" value={this.state.value} onChange={this.handleChange} />
		        </label>
		        <input type="submit" value="Submit" />
		      </form>
		    );
		  }
		}
	

Uncontrolled Component

It is similar to the traditional HTML form input. The form data is handled here by the DOM itself. It maintains its own state and will be updated as the input value changes. To write an uncontrolled component, you do not need to write an event handler for each state update, and you can use a ref to access the form value from the DOM.

	
		class NameForm extends React.Component {
		  constructor(props) {
		    super(props);
		    this.handleSubmit = this.handleSubmit.bind(this);
		  }

		  handleSubmit(event) {
		    alert('A name was submitted: ' + this.input.value);
		    event.preventDefault();
		  }

		  render() {
		    return (
		      <form onSubmit={this.handleSubmit}>
		        <label>
		          Name:
		          <input type="text" ref={(input) => this.input = input} />
		        </label>
		        <input type="submit" value="Submit" />
		      </form>
		    );
		  }
		}
	

If you want to create an uncontrolled component in React, we can use ref to get the values. Here we can see that the value in the < input > element is stored in itself, and the value is passed only when the form is submitted, which triggers the handleSubmit function in the form element of the Submit attribute. The handleSubmit can normally perform any procedure, such as sending a value through an API, but in this case, it will only display an alert with a value from an uncontrolled component.

Difference table between controlled and uncontrolled component

ControlledUncontrolled
It does not maintain its internal state.It maintains its internal states.
Here, data is controlled by the parent component.Here, data is controlled by the DOM itself.
It accepts its current value as a prop.It uses a ref for their current values.
It allows validation control.It does not allow validation control.
It has better control over the form elements and data.It has limited control over the form elements and data.
  • Components – React components subscribe to the store in flux whereas in redux, container components utilize connect
  • Dispatcher – There is no dispatcher in redux. On the other hand, flux has a singleton dispatcher
  • Number of Stores – While flux has several stores, there is only a single store for redux
  • State – It is mutable for flux but immutable for redux
  • Store – Influx, the store contains state as well as change logic. Contrary to this, the store in redux is separate from the change logic
  • Store Type – All stores in flux are disconnected and flat. This is not the case with redux, where there is a single store with hierarchical reducers

Render() is used to update the UI. To do this, you need to create a new element and send it to ReactDOM.render). React elements are immutable and you can not change their attributes once you create an element. Thus, the elements are like a single frame, and the UI is shown at some point. ReactDOM.render) (controls the contents of the container node that you pass, and if there is any DOM element already present in it, it will be replaced when you first call it.

What is Redux?

Redux has one main advantage, and that's the efficiency it provides. Redux allows you to store your state in what is called a "Redux Store" and uses actions to call reducers, which in turn manipulate your state however you see fit.

Refer to a neighbor in the conventional prop lane. Imagine, if you need anything from the grocery store, ask neighbor E, ask neighbor D, ask neighbor B, ask neighbor B, ask neighbor A if you can use some of his bread. It works, it works ... Yes, it's very uncomfortable. What if there was only a way for you to receive the bread directly?!

Redux consists of 4 elements:

  1. Store
  2. Reducer
  3. Operation
  4. Middleware

What is a store?

Creating a Store:

Creates a Redux store that holds the complete state tree of our app. We will have a single store in your app.

const store = createStore(reducer, initialState, enhancer)
3 fundamentals to remember:
  1. A store holds the whole state of the application.
  2. The only way, We can change the state inside it is to dispatch an action to it.
  3. A store is not class, it is just an object with a few methods.
Methods of a store:
  1. getState()
  2. dispatch(action)
  3. subscribe(listener)
  4. replaceReducer(nextRducer)

What is a Reducer?

A reducer is a pure function that returns the application status based on the store's dispatch of the action.

When a complex app grows we need multiple reducers to handle each component. Now let's call the reducers combined.

const rootReducert = combineReducer(reducer1, reducer2)
What is an Action?

It is an information payload which transmits data from an application to a store. They represent the store's primary source of information. Using store one can send them to the store. Distribution). Redux is an action that speaks for a simple object with a property named type. Actions are artifacts of free form.

	
		const action =  {
			type: "addEmployee",
			payload
		}
		dispatch(action);
	

What is a Middleware?

Middleware is the suggested way to extend Redux with custom functionality. Middlewares are used to dispatch async functions. We configure Middleware’s while creating a store

const store = createStore(reducers, initialState, middleware);

React.Fragment

Issue

As the React.js docs state, a common pattern in React is for components to return multiple elements. Usually, these elements are wrapped for example inside a div. In most cases the wrapper div is “irrelevant” and is only added because React components require you to return only one element.

Solution

React fragments let us group a list of children without adding extra nodes to the DOM because fragments are not rendered to the DOM.

React.lazy

The React.lazy method makes it easy to code-split a React application on a component level using dynamic imports.

const AvatarComponent = lazy(() => import('./AvatarComponent'));
Why is this useful?

A large React application will usually consist of many components, utility methods, and third-party libraries. If an effort isn't made to try to load different parts of an application only when they're needed, a single, large bundle of JavaScript will be shipped to your users as soon as they load the first page.

The React.lazy function provides a built-in way to separate components in an application into separate chunks of JavaScript with very little legwork. You can then take care of loading states when you couple it with the Suspense component.

Suspense

The problem with shipping a large JavaScript payload to users is the length of time it would take for the page to finish loading, especially on weaker devices and network connections. This is why code splitting and lazy loading is extremely useful.

However, there will always be a slight delay that users have to experience when a code-split component is being fetched over the network, so it's important to display a useful loading state. Using React.lazy with the Suspense component helps solve this problem.

	
		import React, { lazy, Suspense } from 'react';
		const AvatarComponent = lazy(() => import('./AvatarComponent'));
		const InfoComponent = lazy(() => import('./InfoComponent'));
		const MoreInfoComponent = lazy(() => import('./MoreInfoComponent'));
		const renderLoader = () => <p>Loading</p>;
		const DetailsComponent = () => (
		  <Suspense fallback={renderLoader()}>
		    <AvatarComponent />
		    <InfoComponent />
		    <MoreInfoComponent />
		  </Suspense>
		)					
	

Suspense accepts a fallback component which allows you to display any React component as a loading state

Note: React does not currently support Suspense when components are being server-side rendered. If you are rendering on the server, consider using another library such as loadable-components which is recommended in the React docs.

Leave a Comment