Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

React Interview

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 6

what is the diff between react and angular?

reactjs angular
------ ---------
1. it is a library 1. it is a framework.(frameWork
means which provides complete developement solution
like design,databinding,get data from
server,routing,state Management)

(Library means not complete development application


it focus on only one thing and do well like js(lang) and jquery
(library) eg:css is a core lang and boostrap is a library)
it also contain design,data binding but it doesnot provide
the routing and server data calling so we can use best software
for server axios.(3rd party libraries) and for routing react-router-dom

both are not good in state management so we use redux it is developed for js
applications

react ->react-redux angular->ngrx

what is react?

React is a open source frontend js library for building user interfaces based on
components and we have more developer community,it is developed
by facebook developer.

version:18.2.0
why react and why not other frameworks?
1.React’s key features include the ability to use third-party libraries.
2.componental architecure where we can reuse the code modules wherever we
want,lesscode,faster developement,
3.virtual dom(it is a blue print of original dom).(Virtual DOM – anytime the DOM
changes, a new virtual DOM is created, compared to the
previous one, and only the differences are modified in the “real” DOM.)
4.One-directional data binding provides code stability.(One-way data binding means
that a UI element can’t affect a component’s state.)
5.easy to learn.
6.React is comparatively faster than other frameworks. There is a reusability
factor that helps in saving time and money in development.
It supports server-side rendering of websites making it faster by all means

3.what is jsx?
jsx is a extension of java script lnaguage it looks like html but not ,where it is
introduced to overcome the writing of react syntaxes where
the react will convert this jsx into normal javascript language by using babel
(where it converts the jsx to javascript);

4.what is diff between element and component?

element:
=======
1.An element is a plain object describing a component instance or DOM node and its
desired properties. It contains only information
about the component type (for example, a Button), its properties (for example, its
color), and any child elements inside it.
2.

5.how to create componentin react?


in 2 ways we can create the component 1.function 2.class(render() is used)

pure component:(mainly it focus on will component re-render or not if the state or


props are same then it stops rerendering if we use this there is no requirement of
shouldComponentupdate method)
==============
Now, ReactJS has provided us a Pure Component. If we extend a class with Pure
Component, there is no need for shouldComponentUpdate()
Lifecycle Method. ReactJS Pure Component Class compares current state and props
with new props and states to decide whether the React component
should re-render itself or Not.

In simple words, If the previous value of state or props and the new value of state
or props is the same, the component will not re-render
itself. Since Pure Components restricts the re-rendering when there is no use of
re-rendering of the component. Pure Components are
Class Components which extends React.PureComponent.

It is the type of component which re-renders only when the props passed to it
changes and not even if its parent component re-renders or
if the shouldComponentUpdate()method is called. It is greatly used to enhance the
performance of a web application.

In the following example, we are going to use the PureComponent with Comp1
component so that it only re-renders if the props passed to it
changes.

if nested data structures are present in state or props purecomponent will not
work.

in functions we can use usememo.

eg:
The syntactic representation of memoized components looks like below,
const MemoizedComponent = memo(SomeComponent, arePropsEqual?);

Below is the example of how child component(i.e., EmployeeProfile) prevents re-


renders for the same props passed by parent component(i.e.,EmployeeRegForm).

import { memo, useState } from 'react';

const EmployeeProfile = memo(function EmployeeProfile({ name, email }) {


return (<>
<p>Name:{name}</p>
<p>Email: {email}</p>
</>);
});
export default function EmployeeRegForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<>
<label>
Name: <input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Email: <input value={email} onChange={e => setEmail(e.target.value)} />
</label>
<hr/>
<EmployeeProfile name={name}/>
</>
);
}

In the above code, the email prop has not been passed to child component. So there
won't be any re-renders for email prop change.

In class components, the components extending React.PureComponent instead of


React.Component become the pure components. When props or state changes,
PureComponent will do a shallow comparison on both props and state by invoking
shouldComponentUpdate() lifecycle method.

Note: React.memo() is a higher-order component.

import React from 'react';


class App extends React.Component {
constructor() {
super();
this.state = { color: '#000' };
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
<button onClick={() => this.setState({ color: '#ff0000' })}>
Change Color
</button>
<Comp1 />
</div>
);
}
}

class Comp1 extends React.PureComponent {


render() {
alert('Comp1 component is called');
return (
<div>
<h1>Simply Easy Learning</h1>
</div>
);
}
}
export default App;
Output
The above code will generate the following result.

alert will come and tell comp1 is called


What is the difference between state and props?
In React, both state and props are plain JavaScript objects and used to manage the
data of a component, but they are used in different ways
and have different characteristics. state is managed by the component itself and
can be updated using the setState() function.

Unlike props, state can be modified by the component and is used to manage the
internal state of the component. Changes in the state
trigger a re-render of the component and its children. props (short for
"properties") are passed to a component by its parent component and are
read-only, meaning that they cannot be modified by the component itself. props can
be used to configure the behavior of a component and to pass
data between components.

Why should we not update the state directly?


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

//Wrong
this.state.message = "Hello world";
Instead use setState() method. It schedules an update to a component's state
object. When state changes, the component responds by re-rendering.

//Correct
this.setState({ message: "Hello World" });
Note: You can directly assign to the state object either in constructor or using
latest javascript's class field declaration syntax.

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


The callback function is invoked when setState finished and the component gets
rendered. Since setState() is asynchronous the callback function is used for any
post action.
Note: It is recommended to use lifecycle method rather than this callback function.

setState({ name: "John" }, () =>


console.log("The name has updated and component re-rendered")
);

How to bind methods or event handlers in JSX callbacks?


There are 3 possible ways to achieve this in class components:

Binding in Constructor: In JavaScript classes, the methods are not bound by


default. The same rule applies for React event handlers defined as
class methods. Normally we bind them in constructor.

class User extends Component {


constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log("SingOut triggered");
}
render() {
return <button onClick={this.handleClick}>SingOut</button>;
}
}

Public class fields syntax: If you don't like to use bind approach then public
class fields syntax can be used to correctly bind callbacks.
The Create React App eanables this syntax by default.

handleClick = () => {
console.log("SingOut triggered", this);
};

<button onClick={this.handleClick}>SingOut</button>
Arrow functions in callbacks: It is possible to use arrow functions directly in the
callbacks.

handleClick() {
console.log('SingOut triggered');
}
render() {
return <button onClick={() => this.handleClick()}>SignOut</button>;
}
Note: If the callback is passed as prop to child components, those components might
do an extra re-rendering. In those cases, it is preferred to go with .bind() or
public class fields syntax approach considering performance.

9.What is "key" prop and what is the benefit of using it in arrays of elements?
A key is a special attribute you should include when creating arrays of elements.
Key prop helps React identify which items have changed,
are added, or are removed.

Keys should be unique among its siblings. Most often we use ID from our data as
key:

const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);


When you don't have stable IDs for rendered items, you may use the item index as a
key as a last resort:

const todoItems = todos.map((todo, index) => (


<li key={index}>{todo.text}</li>
));
Note:

Using indexes for keys is not recommended if the order of items may change. This
can negatively impact performance and may cause issues with component state.
If you extract list item as separate component then apply keys on list component
instead of li tag.
There will be a warning message in the console if the key prop is not present on
list items.
The key attribute accepts either string or number and internally convert it as
string type.

What is the use of refs?


The ref is used to return a reference to the element. They should be avoided in
most cases, however, they can be useful when you need a
direct access to the DOM element or an instance of a component.

How to create refs?


There are two approaches

This is a recently added approach. Refs are created using React.createRef() method
and attached to React elements via the ref attribute. In order to use refs
throughout the component, just assign the ref to the instance property within
constructor.

class MyComponent extends React.Component {


constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
You can also use ref callbacks approach regardless of React version. For example,
the search bar component's input element is accessed as follows,

class SearchBar extends Component {


constructor(props) {
super(props);
this.txtSearch = null;
this.state = { term: "" };
this.setInputSearchRef = (e) => {
this.txtSearch = e;
};
}
onInputChange(event) {
this.setState({ term: this.txtSearch.value });
}
render() {
return (
<input
value={this.state.term}
onChange={this.onInputChange.bind(this)}
ref={this.setInputSearchRef}
/>
);
}
}
You can also use refs in function components using closures. Note: You can also use
inline ref callbacks even though it is not a recommended approach.

You might also like