React

What is the difference between pure and impure pipe?

A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. An impure pipe is called often, as often as every keystroke or mouse-move.

What is PureComponent? When to use PureComponent over Component?

Pure components are the simplest and fastest components which can be written. They can replace any component which only has a render(). These components enhance the simplicity of the code and performance of the application.

Component and PureComponent have one difference. PureComponent is exactly the same as 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. 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.

So, It is safe to use PureComponent instead of Component so long as you follow two simple rules: 1) Mutations are bad in general, but the problems are compounded when using PureComponent. 2) If you’re creating new functions, objects, or arrays in the render method you’re (probably) doing it wrong.

What is the difference between state and props?

Most of the time, mixing business logic in a React component will provide you with lots of headaches. For example: making an api call and storing those results in state.

Most React patterns (Flux, Redux, etc) will encourage you to keep around datastores (this can be as simple as having a Javascript class separate from your React components). Data involved in business logic gets put in these datastores and a React component will listen to them.

apiReturn() -> datastore.storeData() -> datastore.notifyListeners() -> reactComponentListener()

The listener tends to be on a parent React component which stores that data in state. It then passes it down to child components via props.

Example:

If you have a list of items, your main list component has the listener function which stores the data in state. The components that serve as the items in the list get this data passed in via props.

This keeps a nice separation of logic in your code. The only reason to use state in a child is if you’re doing something simple like a visual toggle.

What is a higher order component?

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

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

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Whereas a component transforms props into UI, a higher-order component transforms a component into another component.

HOCs are common in third-party React libraries, such as Redux’s connect and Relay’s createFragmentContainer().

What is Redux?

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

Virtual DOM?

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

Is setState() is async? Why is setState() in React Async instead of Sync?

Why would they make setState async as JS is single threaded language and this setState is not a WebAPI or server call :

This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.

Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

How Virtual-DOM is more efficient than Dirty checking?

In Matt Esch’s words (who is primary author of virual-dom module), there are in fact 2 problems that need to be solved here:

When do I re-render? Answer: When I observe that the data is dirty.

How do I re-render efficiently? Answer: Using a virtual DOM to generate a real DOM patch.

In React, each of your components have a state. This state is like an observable you might find in knockout or other MVVM style libraries. Essentially, React knows when to re-render the scene because it is able to observe when this data changes. Dirty checking is slower than observables because you must poll the data at a regular interval and check all of the values in the data structure recursively. By comparison, setting a value on the state will signal to a listener that some state has changed, so React can simply listen for change events on the state and queue up re-rendering.

The virtual DOM is used for efficient re-rendering of the DOM. This isn’t really related to dirty checking your data. You could re-render using a virtual DOM with or without dirty checking. You’re right in that there is some overhead in computing the diff between two virtual trees, but the virtual DOM diff is about understanding what needs updating in the DOM and not whether or not your data has changed. In fact, the diff algorithm is a dirty checker itself but it is used to see if the DOM is dirty instead.

We aim to re-render the virtual tree only when the state changes. So using an observable to check if the state has changed is an efficient way to prevent unnecessary re-renders, which would cause lots of unnecessary tree diffs. If nothing has changed, we do nothing.

A virtual DOM is nice because it lets us write our code as if we were re-rendering the entire scene. Behind the scenes we want to compute a patch operation that updates the DOM to look how we expect. So while the virtual DOM diff/patch algorithm is probably not the optimal solution, it gives us a very nice way to express our applications. We just declare exactly what we want and React/virtual-dom will work out how to make your scene look like this. We don’t have to do manual DOM manipulation or get confused about previous DOM state. We don’t have to re-render the entire scene either, which could be much less efficient than patching it.

What is JSX? How do we assign values to JSX attributes? Is it safe to embed user input in JSX?

JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.

Just like XML, JSX tags have a tag name, attributes, and children. If an attribute value is enclosed in quotes, the value is a string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript expression.

It is safe to embed user input in JSX. By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.

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

There are two main types of components in React. Class Components and Functional Components. Class components are ES6 classes and Functional Components are functions. The only constraint for a functional component is to accept props as an argument and return valid JSX.

The key thing that makes functional component different from a class component is the lack of state and lifecycle methods. This is why functional components are also commonly referred to as stateless components.

What is lifecycle method and why it is important?

Around us everything goes through a cycle of taking birth, growing and at some point of time it will die. Consider trees, any software application, yourself, a div container or UI component in a web browser, each of these takes birth, grows by getting updates and dies.

The lifecycle methods are various methods which are invoked at different phases of the lifecycle of a component. Suppose if you are creating the YouTube app, then obviously your app will use the network to buffer the videos and it spends the battery power (let’s assume only these two).
If the user switches to another application after playing the video, then being the awesome developers, you should make sure you are using the resources like network and battery in the most efficient manner. Whenever the user switches to another application, you can stop/pause the buffering of the video, which will stop using the network and battery.

This is what the lifecycle methods in ReactJs provide you, so that the developer can produce a quality application and make sure the developer can really plan what and how to do at various points of birth, growth or death of UI interfaces.

Phases of React Component

There are four phases of a React component. The React component, like anything else in the world, goes through the following phases:

  1. Initialization
  2. Mounting
  3. Update
  4. Unmounting