react interview questions Flashcards
What is React?
It is an open-source front-end JavaScript library most popular for single-page web applications. It is helpful when interactive and complex UIs are built for websites or mobile apps. React.js was released for use in 2015 and since then it has become one of the most trusted and used technologies of recent time. It has built one of the largest developer communities around itself.
List some of React.js’ features.
The major features of React are:
- Uses JSX syntax, a syntax extension of JS that allows developers to write HTML in their JS code.
- It uses Virtual DOM instead of Real DOM considering that Real DOM manipulations are expensive.
- Supports server-side rendering which is useful for Search Engine Optimizations(SEO).
- Follows Unidirectional or one-way data flow or data binding.
Uses reusable/composable UI components to develop the view.
how React’s virtual DOM prevents wasteful DOM manipulation
The Problem
DOM manipulation is the heart of the modern, interactive web. Unfortunately, it is also a lot slower than most JavaScript operations.
This slowness is made worse by the fact that most JavaScript frameworks update the DOM much more than they have to.
As an example, let’s say that you have a list that contains ten items. You check off the first item. Most JavaScript frameworks would rebuild the entire list. That’s ten times more work than necessary! Only one item changed, but the remaining nine get rebuilt exactly how they were before.
Rebuilding a list is no big deal to a web browser, but modern websites can use huge amounts of DOM manipulation. Inefficient updating has become a serious problem.
To address this problem, the people at React popularized something called the virtual DOM.
The Virtual DOM
Here is a refresher of what happens behind the scenes in The Virtual DOM.
In React, for every DOM object, there is a corresponding “virtual DOM object.” A virtual DOM object is a representation of a DOM object, like a lightweight copy.
A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen.
Manipulating the DOM is slow. Manipulating the virtual DOM is much faster because nothing gets drawn onscreen. Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house.
How It Helps
When you render a JSX element, every single virtual DOM object gets updated.
This sounds incredibly inefficient, but the cost is insignificant because the virtual DOM can update so quickly.
Once the virtual DOM has been updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update.
By comparing the new virtual DOM with a pre-update version, React figures out exactly which virtual DOM objects have changed. This process is called “diffing.”
Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM. In our example from earlier, React would be smart enough to rebuild your one checked-off list-item and leave the rest of your list alone.
This makes a big difference! React can update only the necessary parts of the DOM. React’s reputation for performance comes largely from this innovation.
In summary, here’s what happens when you try to update the DOM in React:
- The entire virtual DOM gets updated.
- The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
- The changed objects, and the changed objects only, get updated on the real DOM.
- Changes on the real DOM cause the screen to change.
what is virtual DOM in react?
In React, for every DOM object, there is a corresponding “virtual DOM object.” A virtual DOM object is a representation of a DOM object, like a lightweight copy.
A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen.
Manipulating the DOM is slow. Manipulating the virtual DOM is much faster because nothing gets drawn onscreen. Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house.
source
What Is Server Side Rendering?
Server Side Rendering (SSR) is used to render web pages on the server before sending them to the client. This allows for faster page loads, improved performance, and an SEO-friendly rendering solution for React applications. In addition, SSR can provide a better experience for users with slower internet connections or devices with limited memory and processing power by performing the initial rendering of components on the server.
SSR in React can improve page load times by eliminating unnecessary roundtrips between client and server. Server Side Rendering in React provides more control over how content appears within search engine results pages (SERPs). Since search engine crawlers rely heavily on JavaScript while indexing websites, websites built entirely with Client-Side Rendering may not appear correctly within SERPs due to their inability to parse JavaScript code.
Server Side Rendering, compared to Client-Side Rendering is that it helps ensure consistency across different browsers; since much of modern web development relies heavily upon browser specific features like APIs or custom event handlers – these types of features may not always behave properly when rendered through Client-Side techniques alone but will function normally if prerendered via Server Side methods beforehand.
source
What is unidirectional data flow in React?
Unidirectional data flow describes a one-way data flow where the data can move in only one pathway when being transferred between different parts of the program.
React, a Javascript library, uses unidirectional data flow. The data from the parent is known as props. You can only transfer data from parent to child and not vice versa.
This means that the child components cannot update or modify the data on their own, making sure that a clean data flow architecture is followed. This also means that you can control the data flow better.
source
Advantages of unidirectional data flow in react?
Effect of state changes
In React, each state is owned by one component. Due to the unidirectional flow, the changes made on the state of the component will only affect the children and not the parents or siblings.
Advantages of unidirectional data flow
There are many advantages of unidirectional data flow, some of which are listed below:
Debugging
One-way data flow makes debugging much easier. When the developer knows where the data is coming from and where it is going, they can dry run (or use tools) to find the problems more efficiently.
Better control
Having data flow in one direction makes the program less prone to errors and gives the developer more control.
Efficiency
As the used libraries are wary of the limitations and specifications of the unidirectional flow, extra resources are not wasted, leading to an efficient process.
source
What are the main advantages of React.js?
The main advantages of React.js are:
- It enhances the performance of the application
- It can be used from the client-side as well as the server-side
- The readability of code is higher in React.js because of JSX
- It offers easy integration with frameworks such as Angular, Meteor, etc.
- It is easy to write UI test cases with React.js
If you can include some practical experience demonstrating the advantages of React.js in this React.js interview question, you are likely to impress the recruiter.
what is JSX in react?
JSX stands for JavaScript XML and it is an XML-like syntax extension to ECMAScript. Basically it just provides the syntactic sugar for the React.createElement(type, props, …children) function, giving us expressiveness of JavaScript along with HTML like template syntax.
In the example below, the text inside <h1> tag is returned as JavaScript function to the render function.
export default function App() { return ( <h1 className="greeting">{"Hello, this is a JSX Code!"}</h1> ); }
If you don’t use JSX syntax then the respective JavaScript code should be written as below,
import { createElement } from 'react'; export default function App() { return createElement( 'h1', { className: 'greeting' }, 'Hello, this is a JSX Code!' ); }
Describe an event in React.js?
When a user presses a key, clicks the mouse, or performs any action on the machine or when the machine itself triggers an action, these actions are registered as events in React.js.
In React.js, we use camelCase to name events, instead of the lowercase in HTML
In React.js, because of JSX, a function is passed as an event handler, instead of the string in HTML
For example, in traditional HTML, you might have something like this:
html
<button onclick="handleClick()">Click me</button>
In React.js with JSX, you would write something like this:
<button onClick={handleClick}>Click me</button>
Here, handleClick is a reference to a function defined elsewhere in your code that you want to be executed when the button is clicked. This approach is more inline with JavaScript conventions and allows for more flexibility and maintainability in React applications.
How do Lists work in React.js?
Lists in React.js are created similar to how they are created in regular Javascript. With lists, data can be displayed in an orderly manner and is useful in displaying menus on websites. For traversing lists, the map() function is used. For example,
An array of numbers is taken by the map() function and their value is multiplied by 5
var numbers = [2,4,6,8,10]
const multiplyNums = numbers.map((number => {
return (number*5);
});
console.log (multiplyNums);
Output: The output in Javascript will be logged in the console. The output in the above case is [10, 20, 30, 40, 50]
Why are keys used in React.js Lists?
Keys are used in React.js lists for two primary reasons:
- Efficient Reconciliation: React uses keys to efficiently update the UI when the underlying data changes. When rendering a list of elements, React needs a way to uniquely identify each element in the list. Keys provide a way for React to identify which items have changed, been added, or been removed. This helps React perform a process called reconciliation, where it updates the DOM only for the elements that have changed, rather than re-rendering the entire list.
- Optimizing Rendering Performance: Keys help optimize rendering performance by allowing React to determine which components can be re-used, moved, or removed efficiently. When a list is re-rendered, React compares the keys of the new elements with the keys of the old elements to identify the minimal set of changes needed to update the UI. Without keys, React would have to resort to less efficient methods to track changes in the list.
In summary, keys are essential in React.js lists to enable efficient updates and optimize rendering performance by uniquely identifying list elements and aiding the reconciliation process.
Is HTML used in React?
No, it uses an HTML-in JavaScript syntax called JSX (JavaScript and XML) that converts HTML tags to React elements.
Can you tell two downsides of React?
Steep Learning Curve for Beginners: React introduces a paradigm shift for many developers, especially those coming from a primarily imperative or jQuery background. JSX, component-based architecture, and concepts like state management and props can be challenging to grasp initially. This steep learning curve can slow down the onboarding process for new developers and require significant investment in learning.
Boilerplate Code: While React itself is relatively lightweight, building complex applications often requires integrating with other libraries and tools for state management (such as Redux), routing, form handling, and more. This can lead to a significant amount of boilerplate code, especially for larger applications. Managing this boilerplate code and keeping it organized can add complexity to the project and increase development time and maintenance overhead.
It’s important to note that while these downsides exist, they can often be mitigated with experience, good architectural decisions, and the use of additional tools and libraries within the React ecosystem.
Can you outline the differences between Real DOM and Virtual DOM?
What is Flux?
Flux is a word made up to describe one-way (unidirectional) data flow with very specific events and listeners. There’s no official Flux library, but it’s a pattern we can use react and many works.
there are a lot of components used in Flux. Let’s go through all the components one by one.
View: this component renders the UI. Whenever any user interaction occurs on it (like an event) then it fires off the action. Also when the Store informs the View that some change has occurred, it re-renders itself. For example, if a user clicks the Add button.
Action: this handles all the events. These events are passed by the view component. This layer is generally used to make API calls. Once the action is done it is dispatched using the Dispatcher. The action can be something like add a post, delete a post, or any other user interaction.
The common structure of the payload for dispatching an event is as follows:
{
actionType: “”,
data: {
title: “Understanding Flux step by step”,
author: “Sharvin”
}
}
The actionType key is compulsory and it is used by the dispatcher to pass updates to the related store. It is also a known practice to use constants to hold the value name for actionType key so no typos occur. Data holds the event information that we want to dispatch from Action to Store. The name for this key can be anything.
Dispatcher: this is the central hub and singleton registry. It dispatches the payload from Actions to Store. Also makes sure that there are no cascading effects when an action is dispatched to the store. It ensures that no other action happens before the data layer has completed processing and storing operations.
Consider this component has a traffic controller in the system. It is a centralized list of callbacks. It invokes the callback and broadcasts the payload it received from the action.
Due to this component, the data flow is predictable. Every action updates the specific store with the callback that is registered with the dispatcher.
Store: this holds the app state and is a data layer of this pattern. Do not consider it as a model from MVC. An application can have one or many app stores. Stores get updated because they have a callback that is registered using the dispatcher.
Node’s event emitter is used to update the store and broadcast the update to view. The view never directly updates the application state. It is updated because of the changes to the store.
This is only part of Flux that can update the data. Interfaces implemented in the store are as follows:
- The EventEmitter is extended to inform the view that store data has been updated.
- Listeners like addChangeListener and removeChangeListener are added.
- emitChange is used to emit the change.
what is observer pattern?
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
source
what is redux?
Redux is a pattern and library for managing and updating application state, using events called “actions”. It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.
source
Why Should I Use Redux?
Redux helps you manage “global” state - state that is needed across many parts of your application.
The patterns and tools provided by Redux make it easier to understand when, where, why, and how the state in your application is being updated, and how your application logic will behave when those changes occur. Redux guides you towards writing code that is predictable and testable, which helps give you confidence that your application will work as expected.
source
When Should I Use Redux?
Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There are more concepts to learn, and more code to write. It also adds some indirection to your code, and asks you to follow certain restrictions. It’s a trade-off between short term and long term productivity.
Redux is more useful when:
- You have large amounts of application state that are needed in many places in the app
- The app state is updated frequently over time
- The logic to update that state may be complex
- The app has a medium or large-sized codebase, and might be worked on by many people
how to update an object or an array immutabily in js?
In order to update values immutably, your code must make copies of existing objects/arrays, and then modify the copies.
Is this true or false:
Redux expects that all state updates are done immutably?
true
what is an action in redux?
An action is a plain JavaScript object that has a type field. You can think of an action as an event that describes something that happened in the application.
The type field should be a string that gives this action a descriptive name, like “todos/todoAdded”. We usually write that type string like “domain/eventName”, where the first part is the feature or category that this action belongs to, and the second part is the specific thing that happened.
An action object can have other fields with additional information about what happened. By convention, we put that information in a field called payload.
A typical action object might look like this:
const addTodoAction = {
type: ‘todos/todoAdded’,
payload: ‘Buy milk’
}
source
what are action creators in redux?
An action creator is a function that creates and returns an action object. We typically use these so we don’t have to write the action object by hand every time:
const addTodo = text => {
return {
type: ‘todos/todoAdded’,
payload: text
}
}
what is a reducer in redux?
A reducer is a function that receives the current state and an action object, decides how to update the state if necessary, and returns the new state: (state, action) => newState. You can think of a reducer as an event listener which handles events based on the received action (event) type.
source
what are the rules that a reducer must always follow?
Reducers must always follow some specific rules:
- They should only calculate the new state value based on the state and action arguments
- They are not allowed to modify the existing state. Instead, they must make immutable updates, by copying the existing state and making changes to the copied values.
- They must not do any asynchronous logic, calculate random values, or cause other “side effects”
The logic inside reducer functions typically follows the same series of steps:
- Check to see if the reducer cares about this action
- If so, make a copy of the state, update the copy with new values, and return it
- Otherwise, return the existing state unchanged
Here’s a small example of a reducer, showing the steps that each reducer should follow:
const initialState = { value: 0 } function counterReducer(state = initialState, action) { // Check to see if the reducer cares about this action if (action.type === 'counter/increment') { // If so, make a copy of `state` return { ...state, // and update the copy with the new value value: state.value + 1 } } // otherwise return the existing state unchanged return state }
why reducers are called reducers in redux?
The Array.reduce() method lets you take an array of values, process each item in the array one at a time, and return a single final result. You can think of it as “reducing the array down to one value”.
Array.reduce() takes a callback function as an argument, which will be called one time for each item in the array. It takes two arguments:
previousResult, the value that your callback returned last time
currentItem, the current item in the array
The first time that the callback runs, there isn’t a previousResult available, so we need to also pass in an initial value that will be used as the first previousResult.
If we wanted to add together an array of numbers to find out what the total is, we could write a reduce callback that looks like this:
const numbers = [2, 5, 8] const addNumbers = (previousResult, currentItem) => { console.log({ previousResult, currentItem }) return previousResult + currentItem } const initialValue = 0 const total = numbers.reduce(addNumbers, initialValue) // {previousResult: 0, currentItem: 2} // {previousResult: 2, currentItem: 5} // {previousResult: 7, currentItem: 8} console.log(total) // 15
Notice that this addNumbers “reduce callback” function doesn’t need to keep track of anything itself. It takes the previousResult and currentItem arguments, does something with them, and returns a new result value.
A Redux reducer function is exactly the same idea as this “reduce callback” function! It takes a “previous result” (the state), and the “current item” (the action object), decides a new state value based on those arguments, and returns that new state.
If we were to create an array of Redux actions, call reduce(), and pass in a reducer function, we’d get a final result the same way:
const actions = [ { type: 'counter/increment' }, { type: 'counter/increment' }, { type: 'counter/increment' } ] const initialState = { value: 0 } const finalResult = actions.reduce(counterReducer, initialState) console.log(finalResult) // {value: 3}
We can say that Redux reducers reduce a set of actions (over time) into a single state. The difference is that with Array.reduce() it happens all at once, and with Redux, it happens over the lifetime of your running app.
what is store in redux?
The current Redux application state lives in an object called the store.
The store is created by passing in a reducer, and has a method called getState that returns the current state value:
import { configureStore } from '@reduxjs/toolkit' const store = configureStore({ reducer: counterReducer }) console.log(store.getState()) // {value: 0}
what is dispatch function in redux?
The Redux store has a method called dispatch. The only way to update the state is to call store.dispatch() and pass in an action object. The store will run its reducer function and save the new state value inside, and we can call getState() to retrieve the updated value:
store.dispatch({ type: 'counter/increment' }) console.log(store.getState()) // {value: 1}
You can think of dispatching actions as “triggering an event” in the application. Something happened, and we want the store to know about it. Reducers act like event listeners, and when they hear an action they are interested in, they update the state in response.
We typically call action creators to dispatch the right action:
const increment = () => { return { type: 'counter/increment' } } store.dispatch(increment()) console.log(store.getState()) // {value: 2}
what are selectors in redux?
Selectors are functions that know how to extract specific pieces of information from a store state value. As an application grows bigger, this can help avoid repeating logic as different parts of the app need to read the same data:
const selectCounterValue = state => state.value const currentValue = selectCounterValue(store.getState()) console.log(currentValue) // 2
What is a high order component in React?
In React, a higher-order component is a function that takes a component as an argument and returns a new component that wraps the original component.
HOCs allow you to add additional functionality to a component without modifying the component’s code. For example, you can use a HOC to add authentication or routing capabilities to a component or to apply a specific style or behavior to multiple components.
HOCs can take additional arguments, which lets you customize the behavior of the HOC. This makes them a flexible and reusable way to add functionality to your components.
source
Benefits of Using Higher-Order Components in React?
- Reusability: HOCs allow you to reuse component logic across multiple components, which can save time and reduce code duplication.
- Flexibility: HOCs can take additional arguments, which allows you to customize the behavior of the HOC. This makes them a flexible way to add functionality to your components.
- Separation of concerns: HOCs can help separate concerns in your code by encapsulating certain functionality in a separate component. This can make the code easier to read and maintain.
- Composition: HOCs can be composed together to create more complex functionality. This allows you to build up functionality from smaller, reusable pieces.
- Higher-order components can be used to implement cross-cutting concerns in your application such as authentication, error handling, logging, performance tracking, and many other features.
What is the Presentational segment in react?
Container/Presentational Pattern
In React, one way to enforce separation of concerns is by using the Container/Presentational pattern. With this pattern, we can separate the view from the application logic.
Let’s say we want to create an application that fetches 6 dog images, and renders these images on the screen.
Ideally, we want to enforce separation of concerns by separating this process into two parts:
1. Presentational Components: Components that care about how data is shown to the user. In this example, that’s the rendering the list of dog images.
2. Container Components: Components that care about what data is shown to the user. In this example, that’s fetching the dog images.
Explain Props in ReactJS.
Props in React mean properties. They act as a communication channel from parent to child.
What does super keyword mean in React?
It is used to call super or parent class
List the two types of React component.
Two types of React component are as follows:
- Function component
- Class component
What are synthetic events in ReactJS ?
Synthetic events in React are cross-browser wrappers around the browser’s original event. Different browsers may have different names for the events. They create a uniform interface that React uses to ensure that events execute consistently across browsers. React normalizes this information to provide a consistent API for handling events regardless of the browser.
e.preventDefault() // prevents all the default behavior by the browser. e.stopPropagation() // prevents the call to the parent component whenever a child component gets called.
Note: Here ‘e’ is a synthetic event, a cross-browser object. It is made with a wrapper around the actual event of the browser.
Some of the attributes are:
1. bubbles: Return true or false indicates event is a bubbling event or not.
2. cancelable: Return true or false indicates if the event can be canceled or not.
3. currentTarget: Indicates the element to which the handler is attached
4. defaultPrevented: Return true or false, indicates whether the event has been canceled by preventDefault().
5. eventPhase: Returns number, indicates the phase
6. isTrusted: Return true when the event is generated by the user and false when by the browser/script
7. type: Returns string, it indicates the type of the event
What are three main phases of react component lifecycle?
A component’s lifecycle has three main phases: the Mounting Phase, the Updating Phase, and the Unmounting Phase.
The Mounting Phase begins when a component is first created and inserted into the DOM. The Updating Phase occurs when a component’s state or props change. And the Unmounting Phase occurs when a component is removed from the DOM.
what is component mounting phase?
The mounting phase refers to the period when a component is being created and inserted into the DOM.
During this phase, several lifecycle methods are invoked by React to enable the developer to configure the component, set up any necessary state or event listeners, and perform other initialization tasks.
The mounting phase has three main lifecycle methods that are called in order:
1. constructor()
2. render()
3. getDerivedStateFromProps()
What are stateless components?
If the behaviour of a component 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 the this keyword altogether.
what is jest?
Jest is a well-liked testing tool that makes it simple to test JavaScript applications, particularly those created using JavaScript-based frameworks like React. It is an open-source technology that has won the trust of many developers and is supported by the tech giant Facebook.
Why use Jest to test React Apps?
- Zero Configuration: Jest does not require an extensive configuration before you’re all set to start to test React applications. This is one of Jest’s most useful features, which makes it any developer’s first pick.
- Snapshot Testing: While developers make every effort to implement changes exactly as a designer intended, snapshot testing helps ensure this occurs. The visual representation of a code is recorded and then compared with a screenshot of a new scenario to validate whether there is a difference.
- React Integration: Jest is also mentioned in the official React documentation, emphasizing that it interacts easily with React development. It also works nicely with tools like the React Testing Library, which was created for user-centric testing of React components.
- Community Support: Since Jest is widely utilized in the React development community, there are a ton of resources available to help with any problems one may run into when using Jest to test React applications. The developers benefit from the abundance of instructions and solutions that are available online in numerous forums.
what is callback function?
A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.
Explain React State.
It is an object which stores the component’s property values. Also, it decides how the component renders and behaves.
what are arrow functions in js?
Arrow function {()=>} is concise way of writing JavaScript functions in shorter way. Arrow functions were introduced in the ES6 version. They make our code more structured and readable. Arrow functions are anonymous functions i.e. functions without a name but they are often assigned to any variable
how many ways a state can be updated in react?
it can be updated directly or indirectly. To implement this one can use either this. setState function or the reducer function.
what problem does react context solves?
context api solves the problem of prop drilling.
Prop drilling basically means that in order to pass props from parent to lowest child, we have to make it pass through all the intermediate components also. It means that on every state update, all the intermediary components will be forced to re-render, which badly affects the performance of the application.
for eg- in the below given, image to show the updated user info in the profile screen, new state will be passed down right from app component to the lowest profile component.
what is react 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 users, locale preferences, UI themes need to be accessed in the application by many components.
const { Provider, Consumer } = React.createContext(defaultValue);
how to decide which tool to use: redux or context api in react?
Does React Context replace Redux? The short answer is no, it doesn’t. As we’ve seen, Context and Redux are two different tools, and comparison often arises from misconceptions about what each tool is designed for. Although Context can be orchestrated to act as a state management tool, it wasn’t designed for that purpose, so you’d have to do put in extra effort to make it work. There are already many state management tools that work well and will ease your troubles.
In my experience with Redux, it can be relatively complex to achieve something that is easier to solve today with Context. Keep in mind, prop drilling and global state management is where Redux and Context’s paths cross. Redux has more functionality in this area. Ultimately, Redux and Context should be considered complementary tools that work together instead of as alternatives. My recommendation is to use Redux for complex global state management and Context for prop drilling.
what is webpack?
Webpack in react is a JavaScript module bundler that is commonly used with React to bundle and manage dependencies. It takes all of the individual JavaScript files and other assets in a project, such as images and CSS, and combines them into a single bundle that can be loaded by the browser. Webpack also has the ability to transpile modern JavaScript code (such as ES6) into older versions that can be understood by older browsers.
what is babel?
Babel is a JavaScript compiler
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:
- Transform syntax
- Polyfill features that are missing in your target environment (through a third-party polyfill such as core-js)
- Source code transformations (codemods)
How are ReactJS and React Native different?
Where ReactJS is a front end open-source JavaScript library for UIs, React Native is an open-source mobile framework for platforms such as Android and iOS.
How do browsers read JSX files?
React, a JavaScript library for web applications utilizes JSX—a syntax extension allowing JavaScript objects within HTML elements, enhancing code clarity. JSX isn’t directly supported by browsers, requiring conversion by tools like Babel to transform JSX into valid JavaScript. This transpilation ensures browsers can interpret and execute the JSX-embedded code in React applications.
source
Mention one difference between Props and State.
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.
What is the difference between Element and Component?
An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it cannot be mutated.
The JavaScript representation(Without JSX) of React Element would be as follows:
const element = React.createElement("div", { id: "login-btn" }, "Login");
and this element can be simiplified using JSX
<div id="login-btn">Login</div> The above React.createElement() function returns an object as below: { type: 'div', props: { children: 'Login', id: 'login-btn' } }
Finally, this element renders to the DOM using ReactDOM.render().
Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:
const Button = ({ handleLogin }) => ( <div id={"login-btn"} onClick={handleLogin}> Login </div> );
Then JSX gets transpiled to a React.createElement() function tree:
const Button = ({ handleLogin }) => React.createElement( "div", { id: "login-btn", onClick: handleLogin }, "Login" );
How to create components in React?
Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.
Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the first parameter and return React elements to render the output:
function Greeting({ message }) { return <h1>{`Hello, ${message}`}</h1>; }
Class Components: You can also use ES6 class to define a component. The above function component can be written as a class component:
class Greeting extends React.Component { render() { return <h1>{`Hello, ${this.props.message}`}</h1>; } }
When to use a Class Component over a Function Component?
After the addition of Hooks(i.e. React 16.8 onwards) it is always recommended to use Function components over Class components in React. Because you could use state, lifecycle methods and other features that were only available in class component present in function component too.
But even there are two reasons to use Class components over Function components.
- If you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries.
- In older versions, If the component needs state or lifecycle methods then you need to use class component.
Note: You can also use reusable react error boundary third-party component without writing any class. i.e, No need to use class components for Error boundaries.
The usage of Error boundaries from the above library is quite straight forward.
Note when using react-error-boundary: ErrorBoundary is a client component. You can only pass props to it that are serializeable or use it in files that have a “use client”; directive.
"use client"; import { ErrorBoundary } from "react-error-boundary"; <ErrorBoundary fallback={<div>Something went wrong</div>}> <ExampleApplication /> </ErrorBoundary>
What are Pure Components?
Pure components are the components which render the same output for the same state and props. In function components, you can achieve these pure components through memoized React.memo() API wrapping around the component. This API prevents unnecessary re-renders by comparing the previous props and new props using shallow comparison. So it will be helpful for performance optimizations.
But at the same time, it won’t compare the previous state with the current state because function component itself prevents the unnecessary rendering by default when you set the same state again.
What is state in React?
State of a component is an object that holds some information that may change over the lifetime of the component. The important point is whenever the state object changes, the component re-renders. It is always recommended to make our state as simple as possible and minimize the number of stateful components.
State is similar to props, but it is private and fully controlled by the component ,i.e., it is not accessible to any other component till the owner component decides to pass it.
What are props in React?
Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation similar to HTML-tag attributes. Here, the data is 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 component.
- Trigger state changes.
- Use via this.props.reactProp inside component’s render() method.
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") );
What is the difference between HTML and React event handling?
Below are some of the main differences between HTML and React event handling,
In HTML, the event name usually represents in lowercase as a convention:
<button onclick="activateLasers()"></button>
Whereas in React it follows camelCase convention:
<button onClick={activateLasers}>
In HTML, you can return false to prevent default behavior:
<a href="#" onclick='console.log("The link was clicked."); return false;' />
Whereas in React you must call preventDefault() explicitly:
function handleClick(event) { event.preventDefault(); console.log("The link was clicked."); }
In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer “activateLasers” function in the first point for example)
t
How to pass a parameter to an event handler or callback?
You can use an arrow function to wrap around an event handler and pass parameters:
<button onClick={() => this.handleClick(id)} />
This is an equivalent to calling .bind:
<button onClick={this.handleClick.bind(this, id)} />
Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function
<button onClick={this.handleClick(id)} />; handleClick = (id) => () => { console.log("Hello, your ticket number is", id); };
What are synthetic events in React?
SyntheticEvent is a cross-browser wrapper around the browser’s native event. Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. The native events can be accessed directly from synthetic events using nativeEvent attribute.
Let’s take an example of BookStore title search component with the ability to get all native event properties
function BookStore() { handleTitleChange(e) { console.log('The new title is:', e.target.value); // 'e' represents synthetic event const nativeEvent = e.nativeEvent; console.log(nativeEvent); e.stopPropogation(); e.preventDefault(); } return <input name="title" onChange={handleTitleChange} /> }
What are inline conditional expressions?
You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.
<h1>Hello!</h1>; { messages.length > 0 && !isLogin ? ( <h2>You have {messages.length} unread messages.</h2> ) : ( <h2>You don't have unread messages.</h2> ); }
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 mapping over arrays to render data. 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:
1. 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.
2. If you extract list item as separate component then apply keys on list component instead of li tag.
3. There will be a warning message in the console if the key prop is not present on list items.
4. 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.
what are react refs?
Refs in React are short for references. As the name suggests, they allow you to reference and interact with DOM nodes or React components directly. Refs come in handy when you need to reference some information in a component, but you don’t want that information to trigger new renders.
Common use cases of React refs include:
- Managing focus, text selection, or media playback
- Triggering imperative animations
- Integrating with third-party DOM libraries
how to create refs in react?
In React, Refs can be created by using either the createRef method or the useRef Hook.
Creating Refs using the useRef Hook
You can create refs using the useRef Hook, which is available as part of the React library. Here’s an example of creating a reference in a functional component:
import React, { useRef } from "react"; function ActionButton() { const buttonRef = useRef(null); function handleClick() { console.log(buttonRef.current); } return ( <button onClick={handleClick} ref={buttonRef}> Click me </button> ); }; export default ActionButton;
In the code snippet above, we used the useRef() Hook to create a reference to the button element, which we named buttonRef. This reference enables us to access the current value of buttonRef using buttonRef.current. One advantage of using a ref is that it maintains its state across renders, making it a valuable tool for storing and updating values without causing unnecessary re-renders.
What are forward refs?
Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.
const ButtonElement = React.forwardRef((props, ref) => ( <button ref={ref} className="CustomButton"> {props.children} </button> )); // Create ref to the DOM button: const ref = React.createRef(); <ButtonElement ref={ref}>{"Forward Ref"}</ButtonElement>;
How Virtual DOM works?
The Virtual DOM works in three simple steps.
- Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
- Then the difference between the previous DOM representation and the new one is calculated.
- Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
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 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.
from documentation
Its main goals are:
- Ability to split interruptible work in chunks.
- Ability to prioritize, rebase and reuse work in progress.
- Ability to yield back and forth between parents and children to support layout in React.
- Ability to return multiple elements from render().
- Better support for error boundaries.
What are 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()}) }
What are uncontrolled components?
The Uncontrolled Components are the ones that store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
In the below UserProfile component, the name input is accessed using ref.
class UserProfile extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.input = React.createRef(); } handleSubmit(event) { alert("A name was submitted: " + this.input.current.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> {"Name:"} <input type="text" ref={this.input} /> </label> <input type="submit" value="Submit" /> </form> ); } }
In most cases, it’s recommend to use controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
What is the difference between createElement and cloneElement?
JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.
What is Lifting State Up in React?
When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.
What are the different phases of component lifecycle after react 16.3 ? Diagram question
What are the different phases of component lifecycle before react 16.3 ? Diagram question
what does componentWillMount function do?
componentWillMount: Executed before rendering and is used for App level configuration in your root component.
what does componentDidMount do?
componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.
what does componentWillReceiveProps do?
componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.
what does shouldComponentUpdate function do?
shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn’t need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.
what does componentWillUpdate do?
componentWillUpdate: Executed before re-rendering the component when there are props & state changes confirmed by shouldComponentUpdate() which returns true.
what does componentDidUpdate do?
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if shouldComponentUpdate() returns false.
what does componentWillUnmount do?
componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.
what does getDerivedStateFromProps do?
getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need a derived state. Worth reading if you need derived state.
what does getSnapshotBeforeUpdate do?
getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by this will be passed into componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.
what does componentWillUnmount do?
componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.
What are Higher-Order Components?
A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature.
We call them pure components because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
HOC can be used for many use cases:
- Code reuse, logic and bootstrap abstraction.
- Render hijacking.
- State abstraction and manipulation.
- Props manipulation.
How to create props proxy for 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 children prop?
In React, the children prop is a special prop that allows components to pass elements or components as children to other components. This enables the creation of composite components, where one component can encapsulate and render other components or elements within it.
Here’s a basic example to illustrate its usage:
// ParentComponent.js import React from 'react'; const ParentComponent = ({ children }) => { return ( <div className="parent"> <h1>This is the parent component</h1> {children} </div> ); }; export default ParentComponent;
In this example, the ParentComponent accepts a children prop and renders it within its own JSX structure.
You can use this ParentComponent in another component like this:
// AnotherComponent.js import React from 'react'; import ParentComponent from './ParentComponent'; const AnotherComponent = () => { return ( <ParentComponent> <p>This is passed as a child to the ParentComponent</p> <button>Click me</button> </ParentComponent> ); }; export default AnotherComponent;
In this example, the <p> and <button> elements, along with any other elements or components passed within the <ParentComponent> tags, become the children of the ParentComponent. They will be rendered inside the ParentComponent wherever the {children} placeholder is located within its JSX.</ParentComponent></button>
How to write comments in React?
The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.
Single-line comments:
<div> {/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */} {`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>
What is the purpose of using super constructor with props argument?
A child class constructor cannot make use of this reference until the super() method has been called. The same applies to ES6 sub-classes as well. The main reason for passing props parameter to super() call is to access this.props in your child constructors.
Passing props:
class MyComponent extends React.Component { constructor(props) { super(props); console.log(this.props); // prints { name: 'John', age: 42 } } }
Not passing props:
class MyComponent extends React.Component { constructor(props) { super(); console.log(this.props); // prints undefined // but props parameter is still available console.log(props); // prints { name: 'John', age: 42 } } render() { // no difference outside constructor console.log(this.props); // prints { name: 'John', age: 42 } } }
The above code snippets reveals that this.props is different only within the constructor. It would be the same outside the constructor.
What is reconciliation?
Reconciliation is the process through which React updates the Browser DOM and makes React work faster. React use a diffing algorithm so that component updates are predictable and faster. React would first calculate the difference between the real DOM and the copy of DOM (Virtual DOM) when there’s an update of components. React stores a copy of Browser DOM which is called Virtual DOM. When we make changes or add data, React creates a new Virtual DOM and compares it with the previous one. This comparison is done by Diffing Algorithm. Now React compares the Virtual DOM with Real DOM. It finds out the changed nodes and updates only the changed nodes in Real DOM leaving the rest nodes as it is. This process is called Reconciliation.
How to set 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 })
}
What would be the common mistake of function being called every time the component renders?
You need to make sure that function is not being called while passing the function as a parameter.
render() { // Wrong: handleClick is called instead of passed as a reference! return <button onClick={this.handleClick()}>{'Click Me'}</button> }
Instead, pass the function itself without parenthesis:
render() { // Correct: handleClick is passed as a reference! return <button onClick={this.handleClick}>{'Click Me'}</button> }
what is lazy function in react?
In React, the lazy function is used for code splitting and lazy loading components. This allows you to load components asynchronously, meaning they are only loaded when they are needed, rather than all at once when the application initializes. Lazy loading is especially useful for large applications where loading all components upfront may lead to longer initial load times.
Here’s how you can use the lazy function:
const MyLazyComponent = React.lazy(() => import('./MyComponent'));
In this example, MyComponent is imported dynamically using the import() function, which returns a Promise. React.lazy takes a function that calls import() and returns a promise for a module containing a React component. When the component is needed, React will then load the component’s module and render it.
You can then use MyLazyComponent as you would any other component:
const App = () => ( <div> <Suspense fallback={<div>Loading...</div>}> <MyLazyComponent /> </Suspense> </div> );
In the above code, <Suspense> is used to wrap the lazy-loaded component. It allows you to specify a fallback UI to display while the lazy component is loading. Once the lazy-loaded component is loaded, it will be rendered in place of the fallback UI.</Suspense>
It’s important to note that lazy loading should be used judiciously, as it adds complexity to the application and can affect user experience if not implemented carefully. It’s typically most beneficial for larger applications where reducing initial load times is a priority.
Is lazy function supports named exports?
No, currently React.lazy function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and don’t pull unused components. Let’s take a component file which exports multiple named components,
// MoreComponents.js export const SomeComponent = /* ... */; export const UnusedComponent = /* ... */;
and reexport MoreComponents.js components in an intermediate file IntermediateComponent.js
// IntermediateComponent.js export { SomeComponent as default } from "./MoreComponents.js";
Now you can import the module using lazy function as below,
import React, { lazy } from "react"; const SomeComponent = lazy(() => import("./IntermediateComponent.js"));
Why React uses className over class attribute?
The attribute class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principle reason why React uses className instead of class. Pass a string as the className prop.
render() { return <span className={'menu navigation-menu'}>{'Menu'}</span> }
What are fragments?
It’s a common pattern or practice in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. You need to use either or a shorter syntax having empty tag (<></>).
Below is the example of how to use fragment inside Story component.
function Story({title, description, date}) { return ( <Fragment> <h2>{title}</h2> <p>{description}</p> <p>{date}</p> </Fragment> ); }
It is also possible to render list of fragments inside a loop with the mandatory key attribute supplied.
function StoryBook() { return stories.map(story => <Fragment key={ story.id}> <h2>{story.title}</h2> <p>{story.description}</p> <p>{story.date}</p> </Fragment> ); }
Usually, you don’t need to use until unless there is a need of key attribute. The usage of shorter syntax looks like below.
function Story({title, description, date}) { return ( <> <h2>{title}</h2> <p>{description}</p> <p>{date}</p> </> ); }
Why fragments are better than container divs?
Below are the list of reasons to prefer fragments over container DOM elements,
- 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.
- Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
- The DOM Inspector is less cluttered.
What are portals in React?
In React, portals provide a way to render children components into a DOM node that exists outside of the parent component’s DOM hierarchy. This means you can render components into a different part of the DOM tree, allowing for more flexible and powerful UI layouts.
Portals are useful for scenarios like modals, tooltips, or any other UI element that needs to visually “break out” of its parent container but still be managed by React.
Here’s a basic example of how you can use portals in React:
import React from 'react'; import ReactDOM from 'react-dom'; // Define a modal component const Modal = ({ children }) => { return ReactDOM.createPortal( children, document.getElementById('modal-root') ); }; // App component using the Modal const App = () => ( <div> <h1>Hello, world!</h1> <Modal> <div> This is a modal content. <button>Close</button> </div> </Modal> </div> ); // Render the App component ReactDOM.render(<App />, document.getElementById('root'));
In this example:
- We define a Modal component that accepts children.
Inside the Modal component, we use ReactDOM.createPortal() to render the children into a separate DOM node with the id modal-root. This node can be located anywhere in the HTML structure, not necessarily a child of the Modal component. - In the App component, we render the Modal component along with other content. The content inside the Modal will be rendered into the modal-root DOM node.
This way, even though the Modal component is declared inside the App component, it’s rendered outside of its DOM hierarchy, allowing for overlays or pop-ups without being constrained by the parent’s styles or layout.
What are stateful components?
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 either function components with hooks or class components.
Let’s take an example of function stateful component which update the state based on click event,
import React, {useState} from 'react'; const App = (props) => { const [count, setCount] = useState(0); handleIncrement() { setCount(count+1); } return ( <> <button onClick={handleIncrement}>Increment</button> <span>Counter: {count}</span> </> ) }
How to apply validation on props in React?
When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It’s disabled in production mode due to performance impact. The mandatory props are defined with isRequired.
The set of predefined prop types:
PropTypes.number
PropTypes.string
PropTypes.array
PropTypes.object
PropTypes.func
PropTypes.node
PropTypes.element
PropTypes.bool
PropTypes.symbol
PropTypes.any
import React from "react"; import PropTypes from "prop-types"; function User({ name, age }) { return ( <> <h1>{`Welcome, ${name}`}</h1> <h2>{`Age, ${age}`}</h2> </> ); } User.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number.isRequired, };
What are the limitations of React?
- React is just a view library, not a full framework.
- There is a learning curve for beginners who are new to web development.
- Integrating React into a traditional MVC framework requires some additional configuration.
- The code complexity increases with inline templating and JSX.
- Too many smaller components leading to over engineering or boilerplate.
What are error boundaries in React v16?
In React, an error boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the whole application. This helps in gracefully handling errors and prevents the entire UI from crashing due to a single component’s error.
Here’s an example of how you can create and use an error boundary with functional components:
import React, { useState } from 'react'; // Error boundary component const ErrorBoundary = ({ children }) => { const [hasError, setHasError] = useState(false); // Error handling logic const componentDidCatch = (error, info) => { console.error('Error caught by error boundary:', error, info); setHasError(true); }; // Fallback UI if (hasError) { return <div>Something went wrong. Please try again later.</div>; } // Render children if no error return children; }; // Error-prone child component const ChildComponent = () => { const handleClick = () => { throw new Error('An error occurred in ChildComponent!'); }; return ( <div> <button onClick={handleClick}>Click to throw error</button> </div> ); }; // App component const App = () => ( <div> <h1>Hello, world!</h1> <ErrorBoundary> <ChildComponent /> </ErrorBoundary> </div> ); export default App;
How are error boundaries handled in React v15?
React v15 provided very basic support for error boundaries using unstable_handleError method. It has been renamed to componentDidCatch in React v16.
What are the recommended ways for static type checking?
Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.
What is the use of react-dom package?
The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:
- render()
- hydrate()
- unmountComponentAtNode()
- findDOMNode()
- createPortal()
What is the purpose of 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 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.
What is ReactDOMServer?
The ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:
renderToString()
renderToStaticMarkup()
For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString to render your root component to a string, which you then send as response.
// using Express import { renderToString } from "react-dom/server"; import MyPage from "./MyPage"; app.get("/", (req, res) => { res.write( "<!DOCTYPE html><html><head><title>My Page</title></head><body>" ); res.write('<div id="content">'); res.write(renderToString(<MyPage />)); res.write("</div></body></html>"); res.end(); });