0% found this document useful (0 votes)
7 views19 pages

React - FAQ Set 2

The document is a FAQ set about React, covering topics such as React Router DOM, Higher-Order Components, useState vs useEffect, and state management techniques. It includes practical examples like a prime number checker, a search box component, and methods for fetching data in both functional and class-based components. The document emphasizes the advantages of using React over traditional HTML and CSS for building dynamic user interfaces.

Uploaded by

Vidya Telugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

React - FAQ Set 2

The document is a FAQ set about React, covering topics such as React Router DOM, Higher-Order Components, useState vs useEffect, and state management techniques. It includes practical examples like a prime number checker, a search box component, and methods for fetching data in both functional and class-based components. The document emphasizes the advantages of using React over traditional HTML and CSS for building dynamic user interfaces.

Uploaded by

Vidya Telugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

React - FAQ Set 2

____________________________________________________________

Q1 : Explain your understanding of react router DOM?

React Router DOM is a library that allows you to handle client-side routing
in a React application. It provides a way to map URLs to components, and
manage the browser's history so that you can navigate between different
parts of your app without a full page reload. This allows you to create a
seamless user experience and improve the performance of your application.
React Router DOM provides a set of components, such as <Link> and
<Route>, that you can use to build your application's routing structure.

Q2 : What do you understand about the Higher order component


in React?

A Higher-Order Component (HOC) is a pattern in React where a component


is used to wrap another component in order to reuse component logic.
HOCs are a way to share component logic across multiple components,
rather than duplicating that logic in every component that needs it.

A higher-order component is a function that takes a component and returns


a new component. The new component has access to the props of the
wrapped component, and can also receive additional props of its own. The
new component can then render the wrapped component, with the added
ability to render additional markup or behavior.

HOCs are a powerful way to handle component reuse, abstract component


logic, and share logic across multiple components. They are also useful for
adding additional functionality, such as authentication or performance
optimization, to existing components.

One example of a common use of HOCs is to handle authentication. A HOC


that handles authentication can be used to wrap multiple components, and
it will ensure that a user is logged in before displaying the wrapped
component.
Q3 : Difference between useState and useEffect ?

useState and useEffect are both hooks in React that allow you to add
functionality to your functional components. However, they serve different
purposes and are used in different ways.

useState is used for managing state in a functional component. It allows you


to add state to your component, and update it in response to user
interactions or other events. It returns an array with two elements: the
current state value, and a function that can be used to update the state.

useEffect is used for managing side-effects in a functional component. A


side-effect is any behavior that is not directly related to the component's
rendering, such as data fetching, subscriptions, or browser APIs. It allows
you to perform these actions in response to changes in the component's
state or props. It takes a callback function as an argument, which will be
called after the component has rendered.

In short, useState is used to handle the state of a component, whereas


useEffect is used to handle the side effects of a component such as fetching
data, subscriptions or browser APIs.

Q4 : Task - Make a prime number checker in react?

Here's an example of a simple React component that checks if a number is


prime:

import React, { useState } from 'react';

const PrimeChecker = () => {


const [number, setNumber] = useState(0);
const [isPrime, setIsPrime] = useState(false);

const handleChange = (event) => {


setNumber([Link]);
}
const checkPrime = () => {
if (number < 2) {
setIsPrime(false);
return;
}

for (let i = 2; i <= [Link](number); i++) {


if (number % i === 0) {
setIsPrime(false);
return;
}
}
setIsPrime(true);
}

return (
<div>
<input type="number" value={number}
onChange={handleChange} />
<button onClick={checkPrime}>Check Prime</button>
<p>{isPrime ? 'Prime' : 'Not Prime'}</p>
</div>
);
};

export default PrimeChecker;

This component has a number input field and a button to check if the
number entered is prime or not. It uses the useState hook to manage the
state of the number and whether or not it's prime. The handleChange
function updates the number state with the value of the input field when the
user types in it. The checkPrime function, called by the button, checks if the
number is prime and updates the state accordingly.
It's a simple example of how to check if a number is prime in react.

Q5 : How to achieve life-cycle methods in functional components?


In React, class-based components have built-in lifecycle methods that are
triggered at specific points during the component's lifecycle, such as when
it's mounted, updated, or unmounted.
Functional components, on the other hand, do not have built-in lifecycle
methods. However, you can achieve similar functionality in functional
components by using React Hooks.

The useEffect hook is the equivalent of lifecycle methods like


componentDidMount, componentDidUpdate, and componentWillUnmount.
It allows you to run side-effects, such as data fetching or subscriptions, at
specific points during the component's lifecycle.

Here's an example of using useEffect to simulate componentDidMount:


import { useEffect } from 'react';

const MyComponent = () => {


const [data, setData] = useState(null);

useEffect(() => {
fetch('[Link]
.then(response => [Link]())
.then(data => setData(data))
}, []); // only run on the initial mount

return <div>{data}</div>
}

In this example, the useEffect hook is used to fetch data from an API when
the component is first mounted. The empty array [] passed as the second
argument to useEffect ensures that the effect only runs on the initial mount
of the component, which is similar to the componentDidMount lifecycle
method.

You can also use the useEffect to simulate componentDidUpdate by passing


a dependency array of the state/props that you want to listen on.

In short, you can achieve lifecycle methods in functional component using


useEffect hook by using the dependencies array and comparing the current
state/props with the previous state/props.
Q6 : Does Browser read JSX directly?

No, the browser does not read JSX directly.


JSX is a syntax extension for JavaScript, it is not a standalone language and
it is not understood by the browser.
In order for the browser to be able to understand and render your React
code, it needs to be transformed from JSX to plain JavaScript.
This is typically done using a transpiler such as Babel, which converts JSX
into regular JavaScript that the browser can understand.

When you use JSX in a React application, the transpiler will convert it into
regular JavaScript function calls or objects that correspond to the elements
and components you've defined.
For example, the following JSX code:

<h1>Hello, World!</h1>

Will be transpiled into this JavaScript code:

[Link]("h1", null, "Hello, World!");

In summary, JSX is not directly understood by the browser, it needs to be


transpiled to JavaScript before it can be run by the browser.

Q7 : What is DOM and how is it related to react?

The Document Object Model (DOM) is a programming interface for HTML


and XML documents. It represents the structure of a document as a tree-
like object, with each element and attribute in the document represented as
a node in the tree. The DOM allows you to manipulate the content and
structure of a document, as well as respond to events that occur in the
document, such as user interactions.

React is a JavaScript library for building user interfaces. React uses the
concept of a virtual DOM, which is a representation of the actual DOM in
memory. When you build a React application, React creates a virtual DOM
and uses it to update the actual DOM in the browser.
React uses the virtual DOM to optimize updates to the actual DOM. When a
component's state or props change, React updates the virtual DOM and
then performs a "diff" to determine which parts of the actual DOM need to
be updated. This process is more efficient than updating the entire DOM
every time something changes, and it helps to improve the performance of
React applications.

In summary, React uses the DOM as the target where it renders the user
interface, but it uses a virtual representation of the DOM to optimize the
updates and improve the performance of the application.

Q8 : Explain different ways to manage states in react?

There are several different ways to manage state in a React application,


including:

● useState hook: This is the most basic way to manage state in a


functional component. It allows you to add state to a component and
update it in response to user interactions or other events. It returns
an array with two elements: the current state value, and a function
that can be used to update the state.
● useReducer hook: This is similar to useState but it's more powerful
and it's more suitable for complex and large state. It allows you to
manage state in a way that's similar to using a reducer function with
the dispatch method in Redux.
● context: This allows you to share state between components without
having to pass props down through multiple levels of the component
tree. It's useful when you want to share state that's not directly
related to the current component, but it can be complex to implement
and it's not recommended to use it unless you really need it.
● Redux: A popular state management library that allows you to manage
the state of your entire application in a centralized store. It uses a
reducer function to update the state and actions to trigger updates. It
can be overkill for simple application but it's very useful for larger and
more complex applications.
● Mobx: A state management library similar to Redux, but it uses a
more reactive approach and it's more focused on performance. It's
also a good option for larger and more complex applications.

In short, for small and simple applications, useState hook is enough, for
complex and large application, useReducer or external libraries such as
Redux or Mobx is recommended.
It's also worth noting that it's not always necessary to use a library for state
management, it depends on the complexity and size of the application and
the developer's preference.

Q9 : How can you find all the missing numbers between 1 and 50
in an array of random elements in React?

There are different ways to find missing numbers in an array of random


elements in React, but one possible approach is to use the
[Link]() and [Link]() methods to create a
new array that contains only the missing numbers:

const randomArray = [10, 30, 20, 40, 35, 45, 15];


const set = new Set(randomArray)
const missingNumbers = [Link](new Array(50), (_, i) => i + 1)
.filter(num => ![Link](num));
[Link](missingNumbers);

You can use this approach to find missing numbers in a functional


component and use it in your application as per your requirement.

In short, you can use Array's filter() and includes() or Set's has() method to
find the missing numbers in an array of random elements in React.

Q10 : Can we fetch data without using hooks in react?

Yes, it is possible to fetch data without using hooks in React. In class-based


components, you can use lifecycle methods such as componentDidMount to
fetch data and update the component's state when the component is first
rendered.

Here's an example of fetching data in a class-based component using the


componentDidMount lifecycle method:

class MyComponent extends [Link] {


constructor(props) {
super(props);
[Link] = {
data: null
};
}

componentDidMount() {
fetch("[Link]
.then(response => [Link]())
.then(data => [Link]({ data }));
}

render() {
return <div>{[Link]}</div>;
}
}

This component fetches data from an API when it's first mounted and
updates the component's state with the response data. The component will
re-render and show the data when it's available.

It's worth noting that, functional component with hooks has many
advantages over class-based component such as being more concise, and
easier to test, reason hooks are recommended by React team. But still, you
can use class-based component to fetch the data and update the
component's state.

Q11 : Create search box (It should display all the products of the
same name) in react?
Here is an example of a simple search box component that filters an array of
products based on the name:

import React, { useState } from 'react';

const SearchBox = ({ products }) => {


const [searchTerm, setSearchTerm] = useState('');
const [filteredProducts, setFilteredProducts] = useState(products);

const handleChange = (event) => {


setSearchTerm([Link]);
}

useEffect(() => {
const results = [Link](product =>
[Link]().includes([Link]())
);
setFilteredProducts(results);
}, [searchTerm, products]);

return (
<div>
<input type="text" value={searchTerm} onChange={handleChange}
placeholder="search product" />
<ul>
{[Link](product => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
};

export default SearchBox;

This component receives an array of products as a prop, and it uses the


useState hook to manage the state of the search term, and the filtered
products.
The handleChange function is used to update the state of the search term as
the user types in the input field.
The useEffect hook is used to filter the products based on the search term,
it compares the searchTerm with the name of products, if it matches it will
be added to the filteredProduct array.
It also uses the map method to render the filtered products in an unordered
list.

You can use this component in other parts of your application and pass the
products array to it as a prop.

In summary, this component uses the useState hook to manage the state of
the searchTerm, filteredProducts and useEffect hook to filter the products
based on the searchTerm, it's a simple example of how you can create a
search box in React.

Q12 : Why we use react instead of Html & CSS?

React is a JavaScript library for building user interfaces, while HTML and
CSS are markup languages and stylesheet languages respectively. React
provides a number of advantages over using just HTML and CSS to build
web applications:

● Reusability: React allows you to create reusable components that can


be used across your application. This promotes modularity and helps
to keep your code organized and maintainable.
● State Management: React allows you to manage the state of your
application in a centralized and efficient way. This makes it easy to
update the UI when the state changes and it also makes it easy to
manage complex interactions and data flow.
● Performance: React uses a virtual DOM to optimize updates to the
actual DOM. This process is more efficient than updating the entire
DOM every time something changes, and it helps to improve the
performance of React applications.
● JSX: React uses JSX, which is a syntax extension for JavaScript. It
allows you to define components using a familiar syntax that looks
similar to HTML. This makes it easy to understand and write the code,
especially for developers who are familiar with HTML.
● Dynamic & Interactive: React provides a way to create dynamic and
interactive user interfaces, this is not possible with just HTML & CSS.
● Community: React has a large and active community, which means
there are many resources available to help you learn and use React,
including tutorials, documentation, and third-party libraries.

In short, React provides a powerful and efficient way to build web


applications with reusable components, state management, performance
optimization, JSX and a large community

Q13 : Why use render in the component?

In React, the render method is used to define the structure and content of a
component. It is called whenever the component's state or props change,
and it's responsible for returning a description of the component's UI.

The render method is a required part of any React component, it's the core
of how React works. It's called when the component is first created, and it's
also called whenever the component's state or props change. React uses the
result of the render method to update the actual DOM and reflect the
changes in the UI.

The render method is a pure function, which means it should not have any
side-effects, such as modifying the component's state or interacting with the
browser APIs. It should only return a description of the component's UI
based on its props and state.

The render method is also where you define the structure and content of the
component, using JSX. JSX is a syntax extension for JavaScript that allows
you to define the structure of the component using a familiar syntax that
looks similar to HTML.

In short, render method is used to define the structure and content of the
component, it's responsible for returning a description of the component's
UI and it's called whenever the component's state or props change, React
uses the result of the render method to update the actual DOM and reflect
the changes in the UI.
Q14 : How to increment value on button click using usestate?

You can use the useState hook in a functional component to increment a


value on button click. Here's an example:

import { useState } from 'react';

const MyComponent = () => {


const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

In this example, the component uses the useState hook to define a count
state variable with an initial value of 0. The component renders a paragraph
element that displays the current count value, and a button element that
when clicked calls the setCount function and increments the value by 1.

You can also use the shorthand operator ++ to increment the value

<button onClick={() => setCount(count => count +


1)}>Increment</button>

In summary, to increment a value on button click using useState you need


to define a state variable with the useState hook, render a button element
and call the setter function of the state variable in the onClick event of the
button and pass the updated value.

Q15 : How to change port in react app?

The default port for a React app created using create-react-app is 3000.
However, you can change the port to a different one by following these
steps:
● Open the [Link] file in the root of your React app.
● In the "scripts" section, locate the "start" script, it should look
something like this:
"start": "react-scripts start"
● Replace "react-scripts start" with "react-scripts start --port your-new-
port"
"start": "react-scripts start --port your-new-port"
● Save the changes and run the app using the new port.
npm start or yarn start

It's also worth noting that if the port is already in use, it will throw an error.
in that case you have to change it to a new port number or stop the process
that is running on that port.

Another way to change the port is by using the .env file, you can create
a .env file in the root of your project and set the PORT variable like this

PORT=3001

This way you can change the port without modifying the [Link] file.

In summary, to change the port in a React app

Q16 : Create a react app of stop watch with min,sec and hours?

Here is an example of a simple stopwatch component that uses the useState


and useEffect hooks to keep track of the minutes, seconds, and hours:

import React, { useState, useEffect } from 'react';

const Stopwatch = () => {


const [minutes, setMinutes] = useState(0);
const [seconds, setSeconds] = useState(0);
const [hours, setHours] = useState(0);
const [isRunning, setIsRunning] = useState(false);

useEffect(() => {
let interval = null;
if (isRunning) {
interval = setInterval(() => {
if (seconds < 59) {
setSeconds(seconds + 1);
} else if (minutes < 59) {
setMinutes(minutes + 1);
setSeconds(0);
} else if(hours < 23){
setHours(hours + 1);
setMinutes(0);
setSeconds(0);
}
}, 1000);
} else if (!isRunning && seconds !== 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isRunning, minutes, seconds, hours]);

return (
<div>
<p>{hours < 10 ? `0${hours}` : hours } : {minutes < 10 ? `0$
{minutes}` : minutes } : {seconds < 10 ? `0${seconds}` : seconds }</p>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? 'Stop' : 'Start'}
</button>
<button onClick={() => {
setMinutes(0);
setSeconds(0);
setHours(0);
}}>
Reset
</button>
</div>
);
};

export default Stopwatch;


In this code, the component uses the useEffect hook to set an interval that
updates the minutes, seconds and hours state variables every second. The
isRunning state variable is used to control the interval, so it starts and stops
when the start/stop button is clicked. The component also has a reset button
that sets the minutes, seconds, and hours back to 0 when clicked.

The component also uses ternary operator to add leading zeroes to the
hours, minutes, and seconds value if they are less than 10, this way it will
look like a regular stopwatch.

This is a simple example of a stopwatch component that uses the useState


and useEffect hooks in React, you can customize it according to your
requirement.

Q17 : Why do we use [Link]?

[Link]() is a method that is used to prevent the default


behavior of an event from occurring.

When an event such as a form submission or a link click happens, the


browser will perform a default action, such as submitting the form or
navigating to the link's href. Calling [Link]() prevents the
browser from performing that default action.

For example, in a form submission, [Link]() is used to stop


the form from submitting to the server and refreshing the page. Instead, it
allows you to handle the form submission with JavaScript, such as
displaying an error message or sending an AJAX request.

Another example is when you are using <a> tag, by default the browser will
navigate to the link's href when you click on it. If you want to handle the
click event using JavaScript, you can call [Link]() to stop the
browser from navigating to the link's href.

It's also possible to use the [Link]() method to stop the


event from propagating to parent elements. It's especially useful when you
have nested elements and you want to handle the event on the specific
element, and not the parent element.
In summary, [Link]() is used to prevent the default behavior
of an event from occurring, it allows you to handle the event using
JavaScript and it's commonly used in form submission, link clicks and other
events that have a default behavior.

Q18 : What are the limitations of react?

React is a powerful and widely-used JavaScript library for building user


interfaces, but like any technology, it has its limitations. Some of the
limitations of React are:

● Complexity: React can be complex for beginners to learn and use,


especially if you are new to JavaScript and web development.
Understanding the concepts such as JSX, Virtual DOM, and
component lifecycle can be challenging.

● Steep learning curve: React has a steep learning curve, you need to
learn the basics of the library before you can start building more
complex applications.

● Overhead: React can add an extra layer of complexity to your


application, especially if you are using other libraries or frameworks.
This can lead to performance issues and increased development time.

● Lack of guidance: React is a flexible library and provides a lot of


freedom to developers, but sometimes this freedom can lead to
confusion. There's no clear guidance on how to structure your code,
so you may have to figure it out yourself.

● Server-side rendering: React can be challenging to set up for server-


side rendering, which can be an issue for some applications.

● Re-rendering: React's automatic re-rendering can be a limitation in


certain situations, for example, when you have a large amount of data
and you want to avoid unnecessary re-renders.
● SEO: React's initial load time is slower than traditional websites,
which can be an issue for search engines when trying to crawl and
index your website.

These are some limitations of React, it's worth noting that these limitations
are not unique to React, and many of them can be mitigated by using
appropriate techniques, libraries, or frameworks. Additionally, React is
constantly evolving and improving. The React team and community are
working to mitigate these limitations and make the framework more
accessible and efficient.

Q19 : "props are mutable", is this statement true?

The statement "props are mutable" is not entirely true. In React, props
(short for "properties") are passed down from a parent component to a child
component and are used to configure the child component.

Props are considered to be a "single-direction" flow of data, which means


that they are passed down from a parent component to a child component
and should not be modified by the child component. This is because the
parent component is responsible for managing the state of the props and
any changes made by the child component could lead to unexpected
behavior.

When a parent component changes its state, it will pass the new state as
props to its children, which will trigger a re-render of the child component.
This is the correct way to update the child component with new data.

So technically speaking, the props are not mutable, they are read-only.
React components are designed to be immutable, this is a key feature that
allows React to efficiently update the UI. If the child component wants to
change the prop passed to it, it should pass the change to the parent
component and let the parent component update the state and pass the new
state to the child component.

It is possible to mutate the props in a component but it's generally


considered to be an anti-pattern and discouraged. This is because it can
lead to confusion and unexpected behavior, making it difficult to understand
how the component works and to debug it.

In summary, Props are not mutable, they are passed down from parent
component to child component and should be treated as read-only by the
child component. Changing props in child component directly is not
recommended and it's considered as an anti-pattern.

Q20 : What are the Restful API's and its advantages?

REST (Representational State Transfer) is a set of architectural principles


and a set of constraints that are usually applied to web services. RESTful
APIs are web services that are built using the REST architectural style.

RESTful APIs typically use the HTTP protocol for communication and
transfer data using the JSON or XML format. They typically have a base
URL, and the endpoints of the API are usually a part of the URL.

Advantages of RESTful APIs are :

Scalability: RESTful APIs are lightweight and easy to scale, which makes
them a good choice for large-scale projects.

Language-independent: RESTful APIs can be accessed and consumed by


any programming language that can make HTTP requests and parse JSON
or XML responses.

Stateless: RESTful APIs are stateless, which means that the server does not
keep track of the state of the client. This makes them easy to cache and
improves the performance of the API.

Easy to Test: Since RESTful APIs are based on the HTTP protocol, they can
be easily tested using tools like Postman.

Loosely coupled: RESTful APIs are loosely coupled, which means that the
client and server do not need to know anything about each other. This
makes it easy to change the implementation of one without affecting the
other.
Easy to document: RESTful APIs have a well-defined structure, which makes
them easy to document.

Caching: RESTful APIs can be cached, which means that the server can
store the response to a request and reuse it when the same request is made
again. This improves the performance of the API.

In summary, RESTful APIs are a way to build web services that are
lightweight, scalable, language-independent, stateless, easy to test, loosely
coupled, and easy to document. They use the HTTP protocol for
communication, and transfer data using JSON or XML format. These
characteristics make RESTful APIs a popular choice for building web-based
applications and services.

You might also like