1. What is React JS?
ReactJS is an open-source JavaScript library. Facebook developed this library on 29 May 2013. It is used to build interactive user interfaces. React’s main function in an application is to manage the view layer of that application, much like the View in a model-view-controller (MVC) paradigm. React.js encourages developers to break down these complex user interfaces into distinct reusable components that serve as the foundation for the entire UI rather than treating the entire UI as a single entity.
2. What are the features of React?
The following are some features of React:
- The ReactJS follows component-based architecture. This architecture enables us to divide the user interface into small reusable components.
- ReactJS uses virtual DOM, which allows us to render the UI elements in a more efficient way.
- JSX, a syntax extension made available by ReactJS, enables programmers to construct HTML-like code inside JavaScript.
- The reconciliation algorithm of React efficiently updates the necessary parts of the User Interface upon a change in state. It reduces unnecessary rendering and also improves performance.
- As data travels from parent to child components, ReactJS encourages a unidirectional data flow, which makes it simple to understand and maintain the state of the application.
3. What are the advantages & disadvantages of React?
Advantages
- We can reuse the components that we create in React.
- The virtual DOM makes rendering more efficient.
- React has a large and active community support.
- The ecosystem of React has a wide range of libraries and tools that makes development easier.
- You can easily integrate React with other frameworks and libraries.
Disadvantages
- React is a library, not a full-fledged library; therefore, it has a lot of dependencies.
- The JSX syntax can be a little confusing for developers.
- It can impact performance due to a large number of components.
- Due to the rapid development cycles, existing documentation soon becomes outdated.
4. Differentiate between Real DOM and Virtual DOM.
Real DOM | Virtual DOM |
Real DOM is an actual structural representation of the HTML DOM. | Virtual DOM is a lightweight replica of the real DOM. |
Manipulation of real DOM is slow and costly. | Manipulation of virtual DOM is faster and more efficient. |
Updating the real DOM is resource intensive and slow. | Updating the virtual DOM is faster and optimized. |
It requires the entire DOM tree to be rendered upon small manipulations and updations, therefore its performance is slow. | Performs diffing and updates only the necessary elements. |
5. What is JSX?
JSX stands for JavaScript XML. People also refer to it as a syntax extension for JavaScript. JSX allows you to write HTML-like code directly into the JavaScript files. JSX helps us to use dynamic data and expressions directly into the component’s markup. It also enables flexible and powerful UI rendering. It makes the creation and manipulation of components easier and more simple for React development.
Also Read JavaScript Interview Questions and Answers
6. Differentiate between State and Props
States | Props |
States are managed and controlled inside the component itself. | Props are passed down from parent to child components. |
States hold data that are specific to components. | Props hold data that is passed from one component to another. |
States can be changed with the help of hooks. | Props are immutable and read-only for the component. |
They can be initialized inside the constructor. | They are defined when the component is rendered. |
States are private and it cannot be accessed outside the component. | Props are accessible by other components. |
7. Differentiate between stateless and stateful components
Stateless Components | Stateful Components |
Stateless components are also known as functional components. | Stateful components are also known as class components. |
They do not have an internal state. | They have an internal state. |
Stateless components depend on the props they receive. | They can manage and update their states on their own. |
They are written as functions. | They are written as ES6 classes. |
They do not have access to βthisβ keyword. | They do have access to βthisβ keyword. |
They re-render whenever their props are changed. | They re-render whenever their state or props are changed. |
8. What are synthetic events in React?
The synthetic events in React are a cross-browser wrapper around the native browser events. The synthetic events ensure consistent event handling across different platforms and browsers. They have the same interface as native events. They also combine the behavior of different browsers into a single API to make sure that the events display consistent properties on different platforms and browsers.
9. Difference between controlled and uncontrolled components?
Controlled Components: The state inside the controlled components is handled by props and event handlers. Controlled components allow precise control over the user input. They are particularly useful for handling complex form logic and synchronization across multiple form fields. Controlled components are easier to debug and have less complex code. They are faster than uncontrolled components.
Uncontrolled Components: Uncontrolled components manage their state by themselves. They offer less control over user input. Also they are difficult to debug and have a complex code.
10. What is the significance of keys in React?
Following are the significance of keys in React.
- Keys in React are special attributes used to uniquely identify and track components within a list or collection.
- React uses keys to optimize the re-rendering process by performing targeted modifications instead of re-rendering the entire list, improving performance.
- Keys help maintain the stability of the state of the component.
- The use of keys minimizes unnecessary DOM manipulations, as React can identify and update specific components efficiently.
- By leveraging keys, React can streamline the rendering process and ensure efficient updates, resulting in better performance and a smoother user experience.
Also Read JavaScript Coding Interview Questions and Answers
11. Explain the lifecycle methods in React
Following are some important lifecycle methods in React.
- Mounting Phase
- constructor(): It initializes the component and also sets the initial state of the component.
- render(): The render method produces JSX/elements that need to be rendered on the screen.
- componentDidMount(): This method is executed as soon as the component is mounted on the DOM
- Updating Phase
- static getDerivedStateFromProps(props, state): This method helps to update the state based on the new props.
- shouldComponentUpdate(nextProps, nextState): This method determines whether a component should re-render.
- render(): In the updating phase, the component uses the render method to re-render with updated data.
- getSnapshotBeforeUpdate(prevProps, prevState): DOM data is captured before modifications are made.
- componentDidUpdate(prevProps, prevState, snapshot): This method is called when the component is successfully updated.
- Unmounting Phase
- componentWillUnmount(): This method is executed before the component is unmounted.
- Error Handling
- static getDerivedStateFromError(): This function updates the state if there is an error while rendering.
- componentDidCatch(): This method handles errors inside the child components.
12. What are Pure Components?
Pure components in React are special types of components in which we do not need to implement the shouldComponentUpdate() lifecycle method manually. The pure component itself implements it automatically. They carry out a shallow comparison of props and states to implement shouldComponentUpdate() method. Pure components prevent unnecessary rendering if the state and props of the pure component stay the same.
13. What are Higher Order Components(HOC)?
Higher Order Components (HOCs) in React are a type of function that accepts a component as an input, and it returns a new enhanced component as output. They enable code reusability and add extra functionality to multiple components without changing their fundamental implementation. HOCs have the ability to alter props, add states, handle lifecycle methods, and provide context to the wrapped component. They can be used to implement cross-cutting concerns like logging, authentication, or data retrieval.
14. Difference between Element and Component?
Element | Component |
An element is a plain object that describes a component. | The component represents a reusable, independent UI building block. |
Elements are created using JSX syntax or React.createElement() method. | Components are created by defining a function or a class. |
They are lightweight and immutable. | They can have state and lifecycle methods. |
It defines the structure and properties of UI. | It defines the rendering logic and behavior of the UI. |
It cannot have event handlers or custom methods. | It can have custom methods as well as event handlers. |
It is not interactive or reusable. | It can have interactive features and it is reusable as well. |
15. What are fragments?
Fragments are a React.js feature that permits grouping multiple elements together without the need for a wrapper parent element. They allow a component’s render function to return numerous elements without generating unnecessary DOM nodes. They eliminate the need for unnecessary div wrappers and also improve code readability and maintainability. They are denoted by the syntax ‘<React.Fragment>‘ or the alternative syntax ‘<>‘. Fragments come in handy while mapping over arrays or returning a list of elements.
16. What is the definition of Styled Components?
Styled Components.js is a popular library in React that allows us to write CSS directly within the JavaScript code. It helps us to create an encapsulated and reusable styling for React components. This method streamlines styling management, eliminates class naming conflicts, and increases component reusability. It integrates easily with React’s component model and provides an effective solution for styling components clearly.
17. What are hooks, and why were they introduced?
In ReactJS version 16.8, hooks are a new feature that has been included. You can implement features like state, context, side effects, and lifecycle methods in functional components using hooks. Additionally, hooks can be employed to extract stateful logic from components. You can independently check and reuse this logic. Hooks allow you to reuse stateful functionality without having to change the structure of your components. This makes it easier to share states across various components.
18. What do you understand about Virtual DOM? Explain how it works.
The Virtual DOM is a lightweight, in-memory replica of the real DOM. It is made up of JavaScript objects that replicate the structure of the DOM elements rendered by React components. Virtual DOM enables React to efficiently update the actual DOM by representing it with a lightweight, in-memory structure. The Virtual DOM is not confined to browsers. It also finds use in other environments. It makes React a versatile framework for designing user interfaces across multiple platforms.
Working of Virtual DOM
- As soon as there is a change in any underlying data the complete UI is re-rendered in the Virtual DOM form.
- Later we calculate the difference between the new virtual DOM and the previous DOM.
- Depending on the calculations, the real DOM will undergo changes only for the items that have genuinely changed.
19. Can browsers read a JSX file?
No, browsers cannot read JSX files directly. Browsers are designed to interpret and render HTML, CSS, and JavaScript. React employs JSX as a syntax extension to enable the writing of HTML-like code within JavaScript. JSX is not a valid JavaScript or HTML, so browsers cannot understand it directly. The JSX code requires transpilation or compilation into standard JavaScript code, which browsers can interpret. Developers use tools like Babel to convert JSX into JavaScript function calls.
20. How is React different from Angular?
React | Angular |
React is a JavaScript library. | Angular is a full-fledged framework. |
React works on component-based architecture. | Angular works on module based architecture. |
File sizes are smaller. | File sizes are relatively larger. |
It has a unidirectional flow of data. | It follows bidirectional data binding. |
It has a rich ecosystem with numerous tools and libraries. | Integrated tooling and inclusive ecosystem. |
Developed by Facebook. | Developed by Google. |
21. What are the different phases of React component’s lifecycle?
A component’s lifecycle in React consists of multiple phases that represent distinct stages of its existence. These phases are classified into three major categories:
- Mounting: This phase occurs when a component instance is created and inserted into the DOM. The lifecycle methods in this phase include constructor, static getDerivedStateFromProps, render, and componentDidMount.
- Updating: When modifications are made to props or state and a component is re-rendered, this phase gets initiated. Lifecycle methods of this phase include getSnapshotBeforeUpdate, shouldComponentUpdate, getDerivedStateFromProps, render, componentDidUpdate.
- Unmounting: When a component gets removed from the DOM, this process occurs. The componentWillUnmount method represents the lifecycle method of this phase.
22. How does rendering work in React?
Rendering holds immense importance in React as it necessitates the rendering of each component to establish the UI. The render() function undertakes all rendering tasks within React. Upon invocation of the function, it produces an element that represents a DOM component. We can also render many HTML elements inside this render function.
23. What is the use of an arrow function in React?
The following are some of the important use of arrow functions in React:
- Declaring Event Handlers: In React components, developers often use arrow functions to construct event handler functions. They assist in maintaining the right reference to the component’s instance (βthisβ) without the need for manual binding.
- Passing Callbacks: They are useful when passing callbacks as props to child components.
- Creating Inline Functions: You can create inline functions using arrow functions within component render methods or other lifecycle methods.
- Concise Syntax: Arrow functions have a shorter syntax than conventional function declarations.
The following is an example where we are using an arrow function instead of using a conventional method.
// instead of writing this
<input onChange={this.handleChange.bind(this) } />
// we can write this
<input onChange={ (e) => this.handleOnChange(e) } />
24. What is the meaning of create-react-app in React?
The create-react-app is a command-line tool in React. This tool allows you to create a new React application with a predefined setup that includes the required file structure, build scripts, and development server. This allows developers to start constructing React applications immediately without having to spend time on manual setup and configuration.
25. What are events in React?
The actions such as pressing a key on the keyboard, hovering the mouse, clicking the mouse button, etc trigger events. The events in react perform some activities in response to those actions. A user or a system triggers some actions or occurrences, which are referred to as events. Event and event handlers in react help developers to make interactive and responsive user interfaces.
26. What are refs in React?
In React, people refer to refs as references. It helps us to interact and access directly with the react components and DOM elements. Developers use them to maintain a reference to a specific React component or element. Refs find common use in accessing and modifying elements that exist outside the regular data flow of React, like focusing input fields, initiating animations, or interacting with third-party libraries.
27. What are the prop types in React, and how can you validate them?
The prop types offer a mechanism that guarantees the proper datatype of the value passed as props. In simpler terms, React utilizes this feature for type-checking, ensuring the validation of props passed to a React component. To validate prop types, we need to install the prop-types package in our react application. With the help of the following command, we can install the prop-types package in our react application.
npm install prop-types
In the following way, we can validate the prop types in react.
import PropTypes from 'prop-types';
function User(props) {
// Define prop types
User.propTypes = {
firstName: PropTypes.string.isRequired,
lastName: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
email: PropTypes.string,
isAdmin: PropTypes.bool
};
// Component logic and rendering
// ...
}
28. What is the Use of render() in React?
The render() method serves the purpose of returning the JSX or elements that represent the component’s UI. Based on the component’s present state and props, it specifies how the component should appear. The render() method is automatically triggered when the state or props change or when the parent component is rendered. The render() method is an essential part of the component lifecycle. It tells what to display on the screen when the component is rendered or re-rendered.
29. How to Update the State of a Component in React?
Following are the two ways to update the state of a component in react.
Class Component
import React, { Component } from 'react';
class ClassCounter extends Component{
state = {
cnt: 0
};
incrementCounter(){
this.setState({
cnt: this.state.cnt + 1
});
}
render(){
return(
<div>
<h2>Class Component</h2>
<h3>Counter Value = {this.state.cnt}</h3>
<button onClick={() => this.incrementCounter()}>Click Me</button>
</div>
);
}
}
export default ClassCounter;
Functional Component
import React, { useState } from 'react';
const FunctionalCounter = () => {
const [cnt, setCnt] = useState(0);
return(
<div>
<h2>Functional Component</h2>
<h3>Counter Value = {cnt}</h3>
<button onClick={() => setCnt(cnt+1)} >Click Me</button>
</div>
)
}
export default FunctionalCounter;
30. Difference between createElement and cloneElement?
createElement | cloneElement |
It is used to create a new react element. | It is used to modify or clone existing react elements. |
Used to create new elements from scratch. | Used to create copies of existing elements. |
It does not preserve the refs of the original element. | It preserves the refs of the original element. |
It is suitable for creating new elements with different props | It is suitable for reusing existing elements with modified props. |
31. How do you create a React app?
Make sure to install Node.js on your system before creating a React app. To create a react app, you need to enter the following command in the terminal/command prompt.
npx create-react-app myapp
Now enter the myapp directory using the following command.
cd myapp
Lastly, enter the following command to run the react app.
npm start
32. What are forms in React, and how do you create them?
We use forms to collect and manage user input. Forms allow users to enter data such as numbers, text, select options, or checkboxes and submit it to the server for processing. To create a form in react, follow the following steps.
- First, set up the component that will represent your form.
- Now, add input elements such as ‘input’, ‘textarea’, or ‘select’ to the components render method. When the user inputs or updates data, assign each input a corresponding state value and an onChange event handler to update the state.
- To submit the form, create a form submit handler. Attract this form submit handler to the βonSubmit’ event of the form element.
Following is an example of a simple form in react.
import React, { useState } from 'react';
const SimpleFormComponent = () => {
const [data, setData] = useState({
name:'',
email: ''
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setData(prevState => ({
...prevState,
[name]: value
}));
}
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
};
return(
<div>
<form onSubmit={handleSubmit}>
<input type="text" name="name" value={data.name} onChange={handleInputChange} />
<input type="email" name="email" value={data.email} onChange={handleInputChange} />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default SimpleFormComponent;
33. How do you write comments in React?
We can write comments in react in the following way.
To write comments in javascript code using the following format.
// single-line comment.
/*
Multi-line comment
*/
To write comments in JSX code, use the following format.
{/* This is used for single as well as multi line comments. */}
To write comments that are visible in HTML output, you can use HTML-style comments.
{/* <!-- This is HTML style comment --> */}
34. What are arrow functions, and how do developers use them in React?
The arrow function is a shorthand syntax for writing functions in JavaScript. ECMAScript 6 introduced arrow functions. They became widely used in modern JavaScript development, including in libraries and frameworks like React. Following is a way to use arrow functions in react.
const multiply = (a, b) => {
return a * b;
};
Or we can also write it in the following way.
const multiply = (a, b) => a * b;
35. What are the components in React? And the difference between Functional and Class components.
Components are the fundamental building blocks in react. In React, components serve the purpose of creating user interfaces. They consist of self-contained, reusable chunks of code, each encompassing specific functionality or a section of the user interface. Essentially, components represent custom HTML elements that developers can reuse across an application.
Difference between Functional and Class components
Functional | Class |
Functional components do not have their own state. | Class components have their own state. βthis.stateβ is used to manage the state in class components. |
They do not have lifecycle methods. | They do have lifecycle methods (e.g., componentDidMount, render). |
They are lightweight and faster. | They are heavier and slow to render. |
The syntax of functional components is easy to read and understand. | The syntax of class components is complex. |
36. How can you embed two or more components into one?
Following are the ways to embed two or more components into one.
Method 1
function ParentComponent() {
return (
<div>
<h1>Parent Component</h1>
<ChildComponent1 />
<ChildComponent2 />
</div>
);
}
Method 2
class ComponentA extends React.Component{
render(){
return(
<div>
<h1>Welcome to ExploreUI</h1>
<Title/>
</div>
);
}
}
class Title extends React.Component{
render(){
return
<h1>Top 50 React JS Interview Questions</h1>
};
}
ReactDOM.render(
<ComponentA/>, document.getElementById('root')
);
37. What is a React Router? And how do you implement it?
React Router is a library in React that helps us to handle routes in the application. It provides a simple way to define the routing and navigation behavior of your application. It allows the creation of multiple views or pages within a single-page application.
To implement React Router in your application, you need to install the react-router-dom package. Following is the command to install react-router-dom into your application.
npm install react-router-dom
Setting up the router component
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
Define Routes
import { Route } from 'react-router-dom';
function App() {
return (
<div>
<h1>My App</h1>
<Route exact path="/" component={Home} />
<Route path="/album" component={Album} />
<Route path="/maps" component={Maps} />
</div>
);
}
Creating components for each route
function Home() {
return <h2>Welcome to the Home page!</h2>;
}
function Album() {
return <h2>Album!</h2>;
}
function Maps() {
return <h2>Maps</h2>;
}
38. How do you style React components?
Following are some ways to style components in React.
Inline Styles
Define inline styles as JavaScript objects with camel-cased CSS properties, and then pass them as a prop to the component using the style attribute.
function ComponentA() {
const styles = {
color: 'blue',
fontSize: '25px',
fontWeight: 'normal',
};
return <div style={styles}>Inline Styles</div>;
}
CSS Modules
The CSS Modules help you to write CSS stylesheets and import them into the React Components.
Create a ComponentA.module.css file.
.myClass {
color: red;
}
.myOtherClass {
font-weight: bold;
}
ComponentA.jsx
import styles from './ComponentA.module.css';
function ComponentA() {
return(
<div>
<h1 className={styles.myClass}>Welcome to ExploreUi!</h1>
<p className={styles.myOtherClass}>Top 50 React Interview Questions</p>
</div>
);
}
CSS-in-JS Libraries
Developers frequently style React components using CSS-in-JS libraries like styled-components, Emotion, and CSS Modules. With these libraries, you may dynamically create CSS styles depending on props, state, or other factors and write them directly into your JavaScript code.
import styled from 'styled-components';
const StyledComp = styled.div`
color: red;
font-size: 25px;
font-weight: normal;
`;
function ComponentA() {
return <StyledComp>CSS-in-JS Libraries</StyledComp>;
}
39. State management in React.
Managing and updating data within a component or across components is termed as state management in React. In react, we have two types of components class and functional. Class components have an internal state. ‘this.state’ is utilized to access the state within the class component. Functional components do not have an internal state. Functional components use hooks to manage and update the state. In more sophisticated applications, you can use external libraries like Redux or MobX for centralized state management, enabling components to access and modify shared data.
40. How can you set a state?
Following are the two ways to set a state in react.
Class Component
import React, { Component } from 'react';
class CounterComponent extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
handleClick() {
this.setState({ counter: this.state.counter + 1 });
}
render() {
return (
<div>
<h1>Counter: {this.state.counter}</h1>
<button onClick={() => this.handleClick()}>Increment</button>
</div>
);
}
}
Functional Component
import React, { useState } from 'react';
function CounterComponent() {
const [counter, setCounter] = useState(0);
const handleClick = () => {
setCounter(counter + 1);
};
return (
<div>
<h1>Counter: {counter}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
}
41. What is the context API?
The context API is a special feature in react. It allows us to share data between components. We can share data without explicitly passing it through props at each level of the component tree. Basically, it provides us with a way to create a global state. Any component within its tree can access this global state. It consists of two components. The first component is the provider. It defines the data that components need to share. The second component is the consumer. This component receives the data shared by the provider. Following is an example of context API.
const MyContext = React.createContext();
export default MyContext;
Provider Component
const ProviderComponent = () => {
const val = "Hi from the Producer Component!";
return (
<MyContext.Provider value={val}>
{/* Some other rendering */}
</MyContext.Provider>
);
Consumer Component
const ConsumerComponent = () => {
return (
<MyContext.Consumer>
{(value) => (
<div>
<h1>This is Consumer Component</h1>
<p>Value: {value}</p>
</div>
)}
</MyContext.Consumer>
);
};
42. What are error boundaries in React?
Error boundaries are a special feature in React. This feature helps us to catch and handle errors that occur during the rendering, lifecycle methods, and event handlers of component tree. Using error boundaries actively prevents the entire application from crashing when an unhandled error occurs in a single component. Most commonly, people use them to log errors and display a fallback UI. Following is an example of an error boundary in react.
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { e: false };
}
static getDerivedStateFromError(error) {
return { e: true };
}
componentDidCatch(error, errorInfo) {
console.error(error);
}
render() {
if (this.state.e) {
return <p>Error! Something went wrong</p>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Now wrap this ErrorBoundary component around other components.
43. What can you think of as optimization of your application?
Following are some techniques that are useful in optimizing a react application.
- It is highly recommend to use React Developer Tools. It helps us to detect and fix performance bottlenecks. You can also use it to monitor the performance of individual components and determine which component re-renders the most.
- To avoid unnecessary re-renders, use the shouldComponentUpdate lifecycle method.
- We should replace components with PureComponent Or memo.
- Use the React.memo higher-order component to prevent unnecessary re-renders of functional components by memoizing props.
- Employ the useMemo hook to memoize the results of expensive calculations or transformations within a component.
- Utilize the useCallback hook to prevent unnecessary function re-creation on each render.
- Use setState with functional updates to ensure you’re updating state based on the previous state, reducing potential conflicts and re-renders.
- Utilize the lazy loading method. In this method, you just load the elements required for the current view. This can significantly boost your application’s performance.
- Utilize the code-splitting method. In this strategy, you divide your program into smaller code segments. We load each segment as required.
- Use CSS transitions/animations instead of JavaScript for UI animations.
44. What are the key differences between server-side rendering and client-side rendering in Reactjs?
Server-side rendering | Client-side rendering |
HTML is rendered on the server side before sending it to the client side. | Rendering occurs on the client side in the browser. |
Lower client-side performance as the server handles rendering and sends HTML to the client. | Higher client-side performance as rendering is done on the client’s machine. |
Requires a server or backend infrastructure to handle rendering and respond with HTML. | Requires a backend API to provide data but relies on client-side JavaScript for rendering. |
45. Conditional rendering and list rendering in React?
Conditional rendering: It renders different content or components based on provided conditions. You can use JavaScript expressions or variables to define the conditions. Following is an example of conditional rendering.
const LoginComponent = ({ isLoggedIn }) => {
return (
<div>
{isLoggedIn ? <h1>Welcome to ExploreUI</h1> : <h1>Please log in.</h1>}
</div>
);
};
List rendering: List rendering refers to displaying an iterable or array of components in a dynamic list. You can generate components for each item and iterate through the data using list rendering. Following is an example of list rendering.
const CartComponent = ({ cart }) => {
return (
<ul>
{cart.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
46. What is the significance of having the key prop when rendering a list of elements?
The key prop is a unique attribute provided by react. It helps in distinguishing each item in a list of items. React needs a different key prop for each item when rendering a list of components or elements dynamically via a loop or the map function. Having the key prop is important for enhancing the functionality and effectiveness of React’s virtual DOM reconciliation process. When the underlying data changes, React uses the key prop to efficiently update, reorder, or remove each component in a list.
47. How do you decide whether to choose Context API or Redux?
Whenever dealing with simpler applications that have a limited amount of shared state and fewer complex state management needs, we advise using the Context API. For larger applications where you have to handle more complex state requirements, time-travel debugging, advanced middleware, or when multiple components need access to the same state, Redux is the recommended choice.
48. How do you pass data from the child component to its parent?
To pass data from the child component to the parent component in react, you need to set a callback function in the parent component. Now pass this callback function as a prop to its child component. The child component can call the callback function, which the parent function sent as a prop, and pass the data as an argument. Using the above-mentioned method, the parent component can receive and handle data from the child component. Following is an example where we are passing data from child component to parent component.
ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const handleDataFromChild = (data) => {
console.log('Data received from child:', data);
};
return (
<div>
<h1>Parent Component</h1>
<ChildComponent onData={handleDataFromChild} />
</div>
);
};
export default ParentComponent;
ChildComponent
import React from 'react';
const ChildComponent = ({ onData }) => {
const sendDataToParent = () => {
const data = 'This data is sent from the child component!';
onData(data);
};
return (
<div>
<h2>Child Component</h2>
<button onClick={sendDataToParent}>Send Data to Parent</button>
</div>
);
};
export default ChildComponent;
49. How do you manage state in components?
State management in components involves storing and updating data within a component. In React, you can manage the state using the built-in hooks for functional components or by extending the Component class and using this.state for class components.
50. How to implement life cycle methods in functional components?
To implement lifecycle methods in functional components of react, we have to make use of the useEffect hook.
Following is an example of the componentDidUpdate life cycle method. We are passing [propValue] as the dependency array to useEffect, it ensures that the effect runs whenever the value of propValue changes it is equivalent to componentDidUpdate.
import './App.css';
import React, {useEffect} from 'react';
function App()
{
useEffect(() => {
// Equivalent to componentDidUpdate
return () => {
// Code here will run before the effect runs next time or when the component is unmounted
};
}, [propValue]);
// component code
return (
// JSX code
);
}
export default App;
Following is an example of the componentDidMount life cycle method. We are passing an empty dependency array ([]) as the second argument to useEffect, it ensures that the effect runs only once it is equivalent to componentDidMount.
import './App.css';
import React, {useEffect} from 'react';
function App()
{
useEffect(() => {
// Equivalent to componentDidMount
return () => {
// Cleanup code (equivalent to componentWillUnmount)
};
}, []);
// component code
return (
// JSX code
);
}
export default App;