React - FAQ Set 1
React - FAQ Set 1
____________________________________________________________
eact is a JavaScript library for building user interfaces. It is used for building reusable
R
UI components and managing the state of those components. React allows developers to
build complex user interfaces by breaking them down into smaller, reusable
components. It is not considered a framework because it does not provide a built-in
structure for application development, unlike Angular or Vue.js. Instead, it focuses on
the view layer of an application and can be easily integrated with other libraries or
frameworks for complete application development.
he useState hook is a built-in hook in React that allows you to add state to functional
T
components. It is an alternative to using the class component syntax and this.state to
manage state in a React application. The useState hook takes an initial state as an
argument and returns an array containing the current state and a setter function for
updating the state.
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
I n this example, the useState hook is used to create a count state variable with an initial
value of 0. The hook returns an array containing the current value of count and a
setCount function that can be used to update the value of count. The component renders
a button that, when clicked, increments the value of the count state variable.
he useState hook is a very powerful tool that allows to manage the state of your
T
component in a simple and efficient way, it's the most basic hook provided by React, but
you can use other hooks like useEffect, useContext, useReducer.. etc to make your
component more complex and handle more complex state.
I n React, props (short for "properties") and state are used to manage the data and
behavior of a component.
rops are used to pass data down from a parent component to its child components.
p
They are considered "read-only" and cannot be modified directly by the child
components. Props are passed to a component as an argument when it is being
rendered, and can be accessed inside the component using the props object.
function ParentComponent() {
const message = 'Hello World';
function ChildComponent(props) {
return <h1>{props.message}</h1>;
}
s tate, on the other hand, is used to manage the internal data and behavior of a
component. It is considered "private" to the component and can only be modified by the
component itself. Unlike props, state can change over time, and when it changes, the
component will re-render to reflect the changes. State is typically used to keep track of
data that can be changed by user interactions or other events.
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
I n this example, the component is using the useState hook to create a count state
variable with an initial value of 0. The component then renders a button that, when
clicked, increments the value of the count state variable.
o sum up, props are used to pass data down from parent components, while state is
T
used to manage the internal data and behavior of a component.
here are a few ways to update the state of a child component from a parent component
T
in React, depending on the specific use case.
ne way is to pass a callback function from the parent component to the child
O
component as a prop. The child component can then call this function when it needs to
update its state, and the parent component can use this function to update the child's
state.
I n this example, the parent component is passing a state prop and a onStateChange
callback function to the ChildComponent.
function ChildComponent(props) {
const handleClick = () => {
props.onStateChange(props.state + 1);
}
return (
<>
<h1>{props.state}</h1>
<button onClick={handleClick}>Increment</button>
</>
);
}
I n this example, the child component is using the handleClick function to call the
onStateChange callback function passed from the parent component, which updates the
child's state.
nother way to update the state in child component is to use the useContext hook,
A
where the parent component creates a context and the child component consume it.
nother way is to use the useReducer hook, where the parent component holds the state
A
and the child component dispatches the action to update the state.
It's depend on the complexity of your application, and the structure you like to use in
your application.
Q5 - Explain your understanding of Prop drilling?
rop drilling, also known as "prop-tunnelling" or "lifting state up," is a technique used
P
in React to pass data and functions down through multiple levels of components.
hen a component needs to pass data or functions to a child component that is several
W
levels down in the component tree, it can pass the data or functions through each
intermediate component as props. This process is known as "prop drilling."
Here is an example:
function ParentComponent() {
const data = { name: 'John', age: 30 };
return (
<ChildA>
<ChildB>
<ChildC data={data} />
</ChildB>
</ChildA>
);
}
I n this example, the ParentComponent is passing a data prop to the ChildC component.
However, the ChildC component is nested several levels deep inside the component tree,
so the data prop needs to be passed through ChildA and ChildB as well. This is prop
drilling.
he problem with prop drilling is that it can make the component tree more complex
T
and harder to understand, as well as make components more dependent on each other.
Also, it can make the component tree less flexible and harder to refactor in the future.
here are several ways to avoid prop drilling such as using the context API and redux to
T
share data between components at different levels of the component tree. It's also
possible to use the useContext hook, which allows you to share data between
components without having to pass it down through props.
It's important to consider the structure of your component tree and to try to minimize
the amount of prop drilling as much as possible in order to make your application more
maintainable and easier to understand.
Q6 - Explain about Life cycle methods?
I n React, a component goes through several stages during its lifetime, from the moment
it is first rendered on the page to the moment it is removed. These stages are known as
the component's "lifecycle." React provides several lifecycle methods that you can use to
add functionality to your components at different points in their lifecycle.
Here are some of the most commonly used lifecycle methods in React:
➔ componentDidMount(): This method is called after the component has been
rendered to the DOM for the first time. This is a good place to perform any setup
that requires the DOM, such as fetching data or setting up event listeners.
➔ componentDidUpdate(prevProps, prevState): This method is called after the
component's props or state have been updated. This is a good place to perform
any additional updates or side effects that depend on the new props or state.
➔ componentWillUnmount(): This method is called just before the component is
removed from the DOM. This is a good place to perform any cleanup that needs
to happen, such as removing event listeners or canceling network requests.
➔ shouldComponentUpdate(nextProps, nextState): This method is called before the
component is re-rendered after an update. It receives the next props and state as
arguments and should return a boolean value indicating whether the component
should update.
➔ render(): This method is the most important lifecycle method. It is called when
the component is first rendered, and whenever the component's props or state
change.
Updated Ans:
There are three main phases in the life cycle of a React component:
ounting: This phase begins when the component is first created and inserted
M
into the DOM. During this phase, React calls the following lifecycle methods in
the following order:
● c onstructor(): This method is called before the component is mounted,
and it is typically used to set up the initial state of the component and to
bind event handlers to the component's methods.
● componentWillMount(): This method is called just before the component
is mounted, and it is typically used to perform any last-minute setup or
configuration.
● render(): This method is called to render the component's JSX and return
a tree of React elements.
● componentDidMount(): This method is called after the component is
mounted and inserted into the DOM. It is typically used to perform any
setup or configuration that requires the component to be fully rendered
and in the DOM, such as fetching data or setting up event listeners.
pdating: This phase begins when the component's state or props change, and it
U
causes the component to re-render. During this phase, React calls the following
lifecycle methods:
nmounting: This phase begins when the component is removed from the DOM.
U
During this phase, React calls the following lifecycle method:
● c omponentWillUnmount(): This method is called just before the
component is unmounted, and it is typically used to perform any cleanup
or configuration that needs to happen before the component is destroyed.
I t's important to note that these lifecycle methods are only available on class
components and are not available on functional components. However, you can use
hooks like useEffect to handle side effects inside functional component and manage the
component life cycle in functional component.
I t's also important to note that some lifecycle methods have been marked as deprecated
and will be removed in future versions of React. It's always a good idea to check the
React documentation and make sure you're using the latest and recommended way of
handling component's lifecycle.
Q7 - what is inside an index.html file in the public folder of react app?
he index.html file located in the public folder of a React app is the root file of the app.
T
It is the file that is served to the browser when the app is loaded. It typically contains the
basic structure of the app's HTML, including the <head> and <body> tags, as well as the
<div> element where the React app will be rendered.
The basic structure of an index.html file for a React app might look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="root"></div>
</body>
</html>
he <div id="root"></div> is the place where the React app will be rendered. The
T
JavaScript files that React application include are usually added to the <head> element,
but the latest versions of create-react-app template include a <script> tag that loads the
JavaScript file at the end of the <body> element, this is to ensure that the app's
JavaScript files are loaded after the HTML has been parsed by the browser.
he index.html file may also include other elements such as <link> tags for styling the
T
app, <meta> tags for SEO, and <script> tags for loading additional libraries or
resources.
I t's also worth noting that the index.html file in a React app is not typically modified
directly, because it's generated by the build process of the react application and is
intended to be used as a template. Any customization that needs to be done to the
HTML file should be done through the index.js file or index.tsx file that imports the
index.html file.
he main idea behind Redux is to keep the state of the application in a single,
T
immutable store. This store can be updated only by dispatching an action, which is an
object that describes a change to the state. The store will then pass the action through a
set of "reducers," which are functions that update the state based on the action.
Redux provides a few key benefits for managing the state of a React application:
● C entralized state management: With Redux, all the state of the application is
stored in a single location, which makes it easy to understand and manage the
state of the entire application.
● Predictable state updates: Redux uses actions and reducers to update the state,
which makes it easy to understand how the state will change in response to a
specific action.
● E asy debugging: Redux provides a way to record the history of actions and state
changes, which makes it easy to understand how the state of the application
changed over time.
● Easy to test: Because actions and reducers are simple functions, they are easy to
test in isolation.
he most common use case for Redux is when an application needs to manage a large
T
amount of state, or when the state needs to be shared between multiple components. It's
especially useful in larger and more complex applications as it provides a way to manage
the state in a scalable and predictable manner.
I t's worth noting that not all React applications need to use Redux, it depends on the
complexity of the application and the way the state is managed. But, it's a powerful tool
that can help you organize your state in a more predictable way and make it easy to
reason about the state of your application.
Single-Page Application (SPA) is a type of web application that loads a single HTML
A
page and dynamically updates the content as the user interacts with the app. Instead of
navigating to different pages, the SPA loads all the necessary code and resources at once
and updates the content in place.
➔
Dynamic updates to the content without requiring a full page refresh
➔ Use of JavaScript to handle client-side logic and interact with the server
➔ Use of a client-side router to handle navigation and update the content in place
➔ Use of AJAX to communicate with the server and update the content dynamically
ne of the most popular frameworks and library to build SPA is React, Angular and
O
Vue.js, they are all JavaScript libraries that allow developers to build dynamic,
interactive user interfaces. These libraries allow you to break down the UI into reusable
components, manage the state of the application, and handle routing.
PAs are becoming increasingly popular because they provide a more seamless and
S
responsive user experience, as well as better performance and offline capabilities. They
are often used for building web-based applications, such as email clients, social media
apps, and e-commerce sites.
I t's worth noting that SPA's also have some disadvantages like SEO, as the search
engines have difficulties indexing the dynamic content of SPAs, and also the loading
time for the initial load of the application.
n application with home, contact us, etc. tabs that uses routes to navigate between
A
different pages can be considered a Single-Page Application (SPA).
he key characteristic of a SPA is that it loads a single HTML page and dynamically
T
updates the content as the user interacts with the app. In the case of the application
you've described, the user is able to navigate between different pages (home, contact us,
etc.) without a full page refresh, which is a key feature of a SPA.
urthermore, the use of JavaScript to handle client-side logic and interact with the
F
server is another common feature of SPAs. In this case, the application uses JavaScript
and routes to dynamically update the content and handle navigation, which is also a
common feature of SPAs.
I n summary, because the application you've described uses routes to navigate between
different pages without a full page refresh, and uses JavaScript to handle client-side
logic, it can be considered a Single-Page Application (SPA).
eact is a JavaScript library for building user interfaces (UI) that is widely used for
R
building web applications. There are several reasons why developers choose to use
React:
➔ Component-based architecture: React allows you to build your UI as a set of
reusable components. This makes the code more maintainable and easier to
understand, and allows for better separation of concerns.
➔ Virtual DOM: React uses a virtual DOM (Document Object Model) to improve the
performance of updates to the UI. The virtual DOM is a lightweight
r epresentation of the actual DOM, and React uses it to determine the minimal set
of updates that need to be made to the actual DOM. This improves the
performance of the application by reducing the number of updates that need to
be made to the DOM.
➔ Easy to learn: React has a relatively simple API, and its component-based
architecture makes it easy to understand and work with. This makes it a good
choice for developers who are new to building web applications.
➔ Large community and ecosystem: React has a large and active community, which
means there are many resources available for learning and troubleshooting.
Additionally, there are many third-party libraries and tools available for React,
which can help speed up development and add additional functionality to your
application.
➔ Flexible: React can be used with other libraries and frameworks, such as Redux
for state management, React Router for client-side routing, and Next.js for
server-side rendering. This flexibility allows developers to choose the tools that
best fit their needs.
➔ Popular in industry: React is widely used by many companies and organizations,
such as Facebook, Airbnb, Netflix, Uber, etc. This means that it's a
well-established technology with a proven track record of success, and that there
are many job opportunities available for React developers.
I n summary, React is a powerful and flexible tool for building web applications, it has a
component-based architecture, uses a virtual DOM for performance, has a large
community, is easy to learn and widely used in the industry.
render() {
return <h1>Hello, World!</h1>;
}
}
his class component, MyComponent, is defined as a JavaScript class that extends the
T
React.Component base class. The render() method returns JSX that will be rendered in
the browser.
lass components have some advantages over functional components, for example, you
C
can use class components to use the lifecycle methods of react, like
componentDidMount, componentWillUnmount, etc.
dditionally, class components can also hold state, and can use a constructor to
A
initialize the state, while functional components can't hold state.
I t's worth noting that the use of class components has been declining in recent years, as
the introduction of hooks in React allows developers to use state and lifecycle methods
in functional components as well.
I t's important to note that you don't have to use class components, you can use
functional components with hooks to achieve the same functionality and it's up to your
preference which one to use.
he virtual DOM (Document Object Model) is a technique used by React to optimize the
T
performance of updates to the UI. The virtual DOM is a lightweight, in-memory
representation of the actual DOM, and React uses it to determine the minimal set of
updates that need to be made to the actual DOM.
hen a component's state changes, React will first create a new virtual DOM tree
W
representing the updated UI. It will then compare this new tree to the previous virtual
DOM tree, and determine the minimal set of changes required to update the actual
DOM. This process is called "reconciliation."
It's worth noting that the virtual DOM is not unique to React,
I n React, a callback hook is a hook that is used to pass a callback function from a parent
component to a child component. The child component can then use the callback
function to communicate with the parent component.
he most common use case for a callback hook is when a child component needs to
T
update the state of a parent component. For example, consider a simple counter
component that increments a count when a button is clicked:
function ParentComponent() {
return (
<>
</>
);
}
allback hooks are also used when a child component needs to notify the parent
C
component of an event, such as when a form is submitted, when a button is clicked, or
when a user changes a value.
I t's worth noting that callback hooks are not unique to React, this pattern is widely used
in other JavaScript libraries and frameworks as well.
I t's also worth noting that callback hooks are used to maintain the unidirectional flow of
data in react, where the data flows from the top-level component to the child
components, and the child component can only update the parent component state
through callback hooks.
seEffect is a hook in React that allows you to synchronize a component with an
u
external system, such as a browser API or a back-end service. It allows you to run side
effects, such as fetching data or setting up event listeners, in a functional component.
seEffect takes two arguments: a callback function and an array of dependencies. The
u
callback function is executed after the component has rendered, and it can contain any
side effects that you want to run. The array of dependencies is a list of values that the
effect depends on.
function MyComponent() {
setData(json);
}
fetchData();
}, []);
}
I n this example, the useEffect hook is used to fetch data from an API and update the
state of the component when the data is received. The empty array [] passed as the
second argument to useEffect means that the effect does not depend on any values and
will only run once, when the component is first rendered.
he use of dependency in useEffect is to re-run the effect whenever the values in the
T
dependency array change, this allows react to re-render the component and update the
state accordingly. If the dependency array is empty or not provided, the effect will run
only on the first render and not on re-render.
function MyComponent({id}) {
useEffect(() => {
setData(json);
}
fetchData();
}, [id]);
}
I n this example, the `useEffect` hook is used to fetch data from an API based on the
`id` prop passed to the component. The `id` prop is included in the dependency array,
which means that the effect will re-run whenever the `id` prop changes. This allows the
component to update the data displayed in the UI when the `id` prop changes.
seContext is a hook in React that allows you to access context from a functional
u
component, while Redux is a library that provides a way to manage the state of an
application in a centralized location, known as the "store."
seContext allows you to share state and functions between components without
u
passing props down through the component tree. Instead, you can create a context
object with a default value and a provider component that wraps the components that
eed access to the context. The consumer components can then use the useContext hook
n
to access the context.
n the other hand, Redux provides a way to manage the state of an application in a
O
centralized store. This store can be updated only by dispatching actions, which are
objects that describe a change to the state. The store will then pass the action through a
set of "reducers," which are functions that update the state based on the action.
edux Toolkit is a set of tools that makes it easier to use Redux in a project, it provides a
R
way to configure a store with the necessary reducers and middlewares, it also provides a
feature called "slice" that allows you to manage specific part of the application state in a
more organized way.
hile useContext and useRedux are both used for state management, they are used for
W
different purposes and at different levels of an application. useContext is typically used
for state management within a component or a group of closely related components,
while Redux is used for global state management across an entire application.
I n summary, useContext is a React hook that allows you to share state and functions
between components, while Redux is a library that provides a way to manage the state of
an application in a centralized location, and Redux Toolkit is a set of tools that makes it
easier to use Redux in a project.
hunks and Sagas are both middleware for Redux that are used to handle side effects,
T
such as API calls and data handling, in a more organized and maintainable way.
thunk is a function that wraps an action and can perform additional logic before or
A
after the action is dispatched. In the case of an API call, for example, a thunk might
handle the logic for making the API request, as well as dispatching other actions to
update the state of the application based on the response.
ere is an example of a thunk that makes an API call and dispatches an action to update
H
the state:
function fetchData() {
} catch (error) {
}
};
}
I n this example, the fetchData thunk is an asynchronous function that dispatches an
action with the type FETCH_DATA_START before making the API call. If the API call is
successful, it dispatches an action with the type FETCH_DATA_SUCCESS and the data
received from the API. If the API call fails, it dispatches an action with the type
FETCH_DATA_ERROR and the error received.
Saga is similar to a thunk, it is a generator function that can be used to handle side
A
effects, such as API calls, in a more organized and maintainable way.
he main difference between them is the way they handle the flow of the actions, thunks
T
are just functions and the flow of actions is done by dispatching actions, while sagas are
generator functions that allows you to handle the flow of actions using the yield
keyword, which makes it easier to follow the sequence of actions, and also allows you to
handle errors and cancellation in a more elegant way.
I n summary, Thunks and Sagas are both middleware for Redux that are used to handle
side effects, such as API calls and data handling, in a more organized and maintainable
way. They are similar in many aspects, the main difference is that thunks use
dispatching actions to handle the flow of actions while sagas use generator functions
and the yield keyword to handle the flow of actions.
Q18 - how would you handle a event in react?
I n React, you can handle events by attaching event listeners to elements in the DOM
using the on syntax. For example, to handle a click event on a button, you would use the
onClick attribute:
function MyComponent() {
console.log('Button clicked!');
};
}
I n this example, the handleClick function is an event handler that will be called when
the button is clicked. The onClick attribute is used to attach the event listener to the
button.
I t's worth noting that React use camelCase for naming events and use on as a prefix for
the event, for example, onClick, onChange, onMouseEnter, etc.
I t's also worth noting that, you can also use arrow functions as event handlers, but it's
not recommended as it will create a new function every time the component re-renders
and will cause unnecessary re-renders, it's better to define event handlers as class
methods or use useCallback hook if using functional components.
function MyComponent() {
console.log('Button clicked!');
}, []);
return <button onClick={handleClick}>Click me</button>;
}
19: Create a simple react apllication, that swaps any two images when I click on
Q
the any one of the images?
function ImageSwap() {
setImage1(image2);
setImage2(image1);
};
setImage1(image2);
setImage2(image1);
};
return (
<div>
<img src={image1} onClick={handleImage1Click} alt="Image 1" />
</div>
);
}
I n this example, the ImageSwap component contains two state variables, image1 and
image2, which are used to store the URLs of the images. The component also contains
two event handlers, handleImage1Click and handleImage2Click, that are used to swap
the images when either image is clicked.
he handleImage1Click function is called when the first image is clicked and it uses the
T
setImage1 and setImage2 state variables to swap the images. The handleImage2Click
function is called when the second image is clicked and it also uses the setImage1 and
setImage2 state variables to swap the images.
ou can replace the image1.jpg and image2.jpg with URLs of your own images and the
Y
component will work as expected.
I t's worth noting that this code is just an example, in a real world application you may
want to handle more complex logic like checking for the current images being displayed,
handling errors in case the images are not loaded, or even using a library like
react-swipeable to handle the swipe events.
Q20 - What are Hooks and it's uses? Tell me about different hooks?
ooks are functions in React that allow you to use state and other React features in
H
functional components. They were introduced in React 16.8 as an alternative to
class-based components. They make it easy to reuse stateful logic and avoid the need for
creating higher-order components or render props.
ooks are used to manage the state and side effects in functional components, and
H
they're also used for code organization.
Here are some of the most commonly used hooks in React:
● u
seState: allows you to add state to a functional component. It returns an array
with two elements: the current state and a setter function to update the state.
● u
seEffect: allows you to synchronize a component with an external system, such
as a browser API or a back-end service. It allows you to run side effects, such as
fetching data or setting up event listeners, in a functional component.
useEffect(() => {
}, [count]);
● u
seContext: allows you to access context from a functional component. It receives
a context object and returns the current context value for that context.
● u
seReducer: allows you to handle complex state updates and it's similar to the
useState hook but it's more powerful, it's a way to handle state updates in a way
similar to using a reducer in Redux.
● u
seCallback: allows you to optimize the performance of your component by
avoiding unnecessary re-renders. It returns a memoized callback.
doSomethingExpensive();
} , [dependency1, dependency2]);
●
● useMemo : allows you to memoize expensive calculations and avoid
re-calculating them on every render. It returns a memoized value.
● const memoizedValue = useMemo(() => expensiveCalculation(a, b), [a, b]);
There are many other hooks available in React, such as:
● u
seRef: allows you to create a reference to a DOM element or a React component
instance, which can be used to access the underlying DOM element or component
instance.
ooks are a powerful feature of React that allows you to build reusable and
H
maintainable code, by allowing you to manage state and side effects in functional
components, and make it easy to share stateful logic between components.
I t's worth noting that hooks should only be called at the top level of a component, and
should not be called inside loops or conditions, this is because hooks rely on the order in
which they are called, and calling them in the wrong order could lead to unexpected
behavior or errors.
lso, it's worth noting that hooks are a relatively new feature and are still being
A
developed, so it's important to stay up to date with any new hooks or updates to existing
hooks that may be released in future versions of React.