You can check all 161 React interview questions here ๐ https://devinterview.io/dev/react-interview-questions
React creates a virtual DOM. When state changes in a component it firstly runs a "diffing" algorithm, which identifies what has changed in the virtual DOM. The second step is reconciliation, where it updates the DOM with the results of diff.
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);
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.
Props are inputs to a React component. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. i.e, They are data passed down from a parent component to a child component.
The primary purpose of props in React is to provide following component functionality:
- Pass custom data to your React component.
- Trigger
state
changes. - Use via
this.props.reactProp
inside component'srender()
method.
For example, let us create an element with reactProp property,
<Element reactProp = "1" />
This reactProp
(or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created using React library.
props.reactProp;
The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when we need direct access to DOM element or an instance of a component.
Jest is a JavaScript unit testing framework made by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing React components.
Below are the advantages of ReactJS:
- Increases the applicationโs performance with Virtual DOM
- JSX makes code is easy to read and write
- It renders both on client and server side
- Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library
- Easy to write UI Test cases and integration with tools such as JEST.
ReactJS is an open-source frontend JavaScript library which is used for building user interfaces especifically for single page applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. ReactJS was first deployed on Facebookโs newsfeed in 2011 and on Instagram.com in 2012.
The comments in ReactJS/JSX is similar to javascript multiline comments which are wrapped with curly braces:
Single-line comments:
<div>
{/* Single-line comments */}
Welcome {user}, Let's play React
</div>
Multi-line comments:
<div>
{/* Multi-line comments for more than
one line */}
Welcome {user}, Let's play React
</div>
The major features of ReactJS are as follows,
- It uses VirtualDOM instead 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
Props are properties that are passed into a child component from its parent, and are readonly.
Class components allows you to use additional features such as local state and lifecycle hooks. Also, to enable your component to have direct access to your store and thus holds state.
When your component just receives props and renders them to the page, this is a stateless component, for which a pure function can be used. These are also called dumb components or presentational components.
componentDidMount
is where an AJAX request should be made in a React component.
This method will be executed when the component โmountsโ (is added to the DOM) for the first time. This method is only executed once during the componentโs life. Importantly, you canโt guarantee the AJAX request will have resolved before the component mounts. If it doesn't, that would mean that youโd be trying to setState on an unmounted component, which would not work. Making your AJAX request in componentDidMount
will guarantee that thereโs a component to update.
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. They are received from above 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.
Presentational components are concerned with how things look. They generally receive data and callbacks exclusively via props. These components rarely have their own state, but when they do it generally concerns UI state, as opposed to data state.
Container components are more concerned with how things work. These components provide the data and behavior to presentational or other container components. They call Flux actions and provide these as callbacks to the presentational components. They are also often stateful as they serve as data sources.
Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.
class UnControlledForm extends Component {
handleSubmit = () => {
console.log("Input Value: ", this.input.value)
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
ref={(input) => this.input = input} />
<button type='submit'>Submit</button>
</form>
)
}
}
Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function.
Itโs often misconstrued that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.
function CustomForm ({handleSubmit}) {
let inputElement
return (
<form onSubmit={() => handleSubmit(inputElement.value)}>
<input
type='text'
ref={(input) => inputElement = input} />
<button type='submit'>Submit</button>
</form>
)
}
- A controlled component has its state completely driven by React,
- Uncontrolled components can maintain their own internal state. E.g., a textarea's value.
A ReactJS 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()
});
}
State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.
Let's create user component with message state,
class User extends React.Component {
constructor(props) {
super(props);
<span class="token cVar">this</span><span class="token cBase">.</span>state <span class="token cBase">=</span> <span class="token cBase">{</span>
message<span class="token cBase">:</span> <span class="token cString">"Welcome to React world"</span><span class="token cBase">,</span>
<span class="token cBase">}</span>
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
}
If the component need state or lifecycle methods then use class component otherwise use functional component.
It has a corresponding element created in the DOM and is connected to that.
It's common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
There is also a shorter syntax which is not supported in many tools
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.
render () {
return (
<ul>
{this.state.todoItems.map(({task, uid}) => {
return <li key={uid}>{task}</li>
})}
</ul>
)
}
Most often you would use IDs from your data as keys. When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort. It is not recommend to use indexes for keys if the items can reorder, as that would be slow.
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 with in constructor.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
And:
class UserForm extends Component {
handleSubmit = () => {
console.log("Input Value is: ", this.input.value)
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
ref={(input) => this.input = input} /> // Access DOM input in handle submit
<button type='submit'>Submit</button>
</form>
)
}
}
We can also use it in functional components with the help of closures.
The state property is updated in a React component with the object passed into setState, and this is done asynchronously. It tells React that this component and its children need to be re-rendered, but React may not do this immediately (it may batch these state update requests for better performance).
If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These Stateful components are always class components and have a state that gets initialized in the constructor.
class App extends Component { constructor(props) { super(props); this.state = { count: 0 }; }
render() { // omitted for brevity } }
JSX is a syntax notation for JavaScript XML(XML-like syntax extension to ECMAScript). It stands for JavaScript XML. It provides expressiveness of JavaScript along with HTML like template syntax. For example, the below text inside h1 tag return as javascript function to the render function,
render(){
return(
<div>
<h1> Welcome to React world!!</h1>
</div>
);
}
Thanks ๐ for reading and good luck on your next tech interview!
Explore 3800+ dev interview question here ๐ Devinterview.io