0% found this document useful (0 votes)
48 views25 pages

React FAQ: Library, Hooks, Props, State

Uploaded by

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

React FAQ: Library, Hooks, Props, State

Uploaded by

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

‭React - FAQ Set 1‬

‭____________________________________________________________‬

‭Q1 - What is React? Is React a library or a framework?‬

‭ 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.‬

‭Q2 - What is the useState hook?‬

‭ 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.‬

‭Here is an example of using the useState hook to create a counter component:‬

‭import { useState } from 'react';‬

‭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.‬

‭Q3 - What are props and 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.‬

‭Here is an example of passing props from a parent component to a child component:‬

‭import ChildComponent from './ChildComponent';‬

‭function ParentComponent() {‬
‭const message = 'Hello World';‬

r‭ eturn <ChildComponent message={message} />;‬


‭}‬

I‭ n this example, the ParentComponent is passing a message prop to the‬


‭ChildComponent. The ChildComponent can then access the message prop using the‬
‭props object:‬

‭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.‬

‭Here is an example of using state in a component:‬

‭import { useState } from 'react';‬

‭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.‬

‭Q4 - how to update states in child component state in parent 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.‬

‭For example, in the parent component:‬


‭function ParentComponent() {‬
‭const [childState, setChildState] = useState(0);‬

‭const handleChildStateChange = (newState) => {‬


‭setChildState(newState);‬
‭}‬

r‭ eturn <ChildComponent state={childState}‬


‭onStateChange={handleChildStateChange} />;‬
‭}‬

I‭ n this example, the parent component is passing a state prop and a onStateChange‬
‭callback function to the ChildComponent.‬

‭In the child component:‬

‭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:‬

‭●‬ c‭ omponentWillReceiveProps(nextProps): This method is called when the‬


‭component receives new props, and it is typically used to update the‬
‭component's state in response to prop changes.‬
‭●‬ ‭shouldComponentUpdate(nextProps, nextState): This method is called‬
‭before the component is updated, and it is typically used to determine‬
‭whether or not the component should be re-rendered.‬
‭●‬ ‭componentWillUpdate(nextProps, nextState): This method is called just‬
‭before the component is updated, and it is typically used to perform any‬
‭last-minute setup or configuration.‬
‭●‬ ‭render(): This method is called to re-render the component with the‬
‭updated state or props.‬
‭●‬ ‭componentDidUpdate(prevProps, prevState): This method is called after‬
‭the component is updated, and it is typically used to perform any cleanup‬
‭or configuration that requires the component to be fully rendered and in‬
‭the DOM.‬

‭ 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">‬

‭<meta name="viewport" content="width=device-width, initial-scale=1.0">‬

‭<title>My React App</title>‬

‭</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.‬

‭Q8 - what is Redux and its application?‬


‭ edux is a JavaScript library that is commonly used in combination with React to‬
R
‭manage the application's state. It provides a way to manage the state of the application‬
‭in a centralized location, known as the "store."‬

‭ 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.‬

‭Q9 - What is SPA?‬

‭ 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.‬

‭Some common features of SPAs include:‬


‭ ‬ ‭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.‬

‭ 10 - A application having home,contact us etc tabs using routes, is it a SPA?‬


Q
‭Give your reasoning?‬

‭ 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.‬

‭ dditionally, the use of routes to handle navigation is a common feature of SPAs. A‬


A
‭client-side router is often used to handle routing in a SPA. The router listens for changes‬
‭to the URL and updates the content in place based on the current route. This allows the‬
‭user to have a seamless experience, as the whole page doesn't need to be reloaded when‬
‭the user navigates to a different page.‬

‭ 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).‬

‭Q11 - Why do we use React?‬

‭ 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.‬

‭Q12 : What is class component in react?‬

I‭ n React, a class component is a way to create a component using a JavaScript class. A‬


‭class component is defined as a JavaScript class that extends the React.Component base‬
‭class, and has a render() method that returns JSX.‬

‭Here's an example of a simple class component in React:‬

‭import React, { Component } from 'react';‬

‭class MyComponent extends Component {‬

‭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.‬

‭Q13 - Explain about Virtual DOM?‬

‭ 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."‬

‭The virtual DOM has several benefits:‬


‭➔‬ ‭Performance: By minimizing the number of updates that need to be made to the‬
‭actual DOM, the virtual DOM can significantly improve the performance of an‬
‭application.‬
‭➔‬ ‭Decoupling: The virtual DOM is decoupled from the actual DOM, which means‬
‭that React can update the UI independently of the browser. This allows React to‬
‭work with different types of rendering environments, such as web, mobile, and‬
‭server-side.‬
‭➔‬ ‭Abstraction: The virtual DOM provides an abstraction layer that allows React to‬
‭update the UI without requiring developers to directly manipulate the actual‬
‭DOM. This makes it easier to write and maintain React components.‬
‭➔‬ ‭Simplifying updates: By comparing the virtual DOM to the previous virtual DOM,‬
‭React can determine the minimal set of changes required to update the actual‬
‭DOM. This makes it easier to reason about and debug the updates being made to‬
‭the UI.‬

‭It's worth noting that the virtual DOM is not unique to React,‬

‭Q14 - what is the use of a callback hook?‬

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() {‬

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

‭return (‬

‭<>‬

‭<ChildComponent onClick={() => setCount(count + 1)} />‬


‭<p>Count: {count}</p>‬

‭</>‬

‭);‬

‭}‬

I‭ n this example, the ParentComponent is passing an onClick callback to the‬


‭ChildComponent. The ChildComponent can then use this callback to increment the‬
‭count when the button is clicked.‬

‭ 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.‬

‭Q15 - Why do we use Useeffect? what is use of dependency in useEffect?‬

‭ 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.‬

‭Here is an example of how to use useEffect to fetch data in a functional component:‬

‭function MyComponent() {‬

‭const [data, setData] = useState([]);‬


‭useEffect(() => {‬

‭async function fetchData() {‬

‭const response = await fetch('https://my-api.com/data');‬

‭const json = await response.json();‬

‭setData(json);‬

‭}‬

‭fetchData();‬

‭}, []);‬

‭return <div>{data.map(item => item.name)}</div>;‬

‭}‬

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.‬

‭Here is an example of how to use useEffect with a dependency:‬

‭function MyComponent({id}) {‬

‭const [data, setData] = useState([]);‬

‭useEffect(() => {‬

‭async function fetchData() {‬


‭const response = await fetch(https://my-api.com/data/${id});‬

‭const json = await response.json();‬

‭setData(json);‬

‭}‬

‭fetchData();‬

‭}, [id]);‬

‭return <div>{data.map(item => item.name)}</div>;‬

‭}‬

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.‬

I‭ n summary, `useEffect` is a hook in React that allows you to synchronize a component‬


‭with an external system, such as a browser API or a back-end service. The use of‬
‭dependency in `useEffect` is to re-run the effect whenever the values in the dependency‬
‭array change, this allows react to re-render the component and update the state‬
‭accordingly.‬

‭Q16 - Explain relation between usecontext hook and redux toolkit?‬

‭ 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.‬

‭Q17 - what is thunks and saga?‬

‭ 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() {‬

‭return async (dispatch) => {‬

‭dispatch({ type: 'FETCH_DATA_START' });‬


‭try {‬

‭const response = await fetch('https://my-api.com/data');‬

‭const data = await response.json();‬

‭dispatch({ type: 'FETCH_DATA_SUCCESS', data });‬

‭} catch (error) {‬

‭dispatch({ type: 'FETCH_DATA_ERROR', 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() {‬

‭const handleClick = () => {‬

‭console.log('Button clicked!');‬

‭};‬

‭return <button onClick={handleClick}>Click me</button>;‬

‭}‬

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() {‬

‭const handleClick = useCallback(() => {‬

‭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?‬

‭import React, { useState } from 'react';‬

‭function ImageSwap() {‬

‭const [image1, setImage1] = useState('image1.jpg');‬

‭const [image2, setImage2] = useState('image2.jpg');‬

‭const handleImage1Click = () => {‬

‭setImage1(image2);‬

‭setImage2(image1);‬

‭};‬

‭const handleImage2Click = () => {‬

‭setImage1(image2);‬

‭setImage2(image1);‬

‭};‬

‭return (‬

‭<div>‬
‭<img src={image1} onClick={handleImage1Click} alt="Image 1" />‬

‭<img src={image2} onClick={handleImage2Click} alt="Image 2" />‬

‭</div>‬

‭);‬

‭}‬

‭export default ImageSwap;‬

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.‬

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

‭●‬ 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(() => {‬

‭document.title = `You clicked ${count} times`;‬

‭}, [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.‬

‭const theme = useContext(ThemeContext);‬

‭●‬ 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.‬

‭const [state, dispatch] = useReducer(reducer, initialArg, init);‬

‭●‬ u
‭ seCallback: allows you to optimize the performance of your component by‬
‭avoiding unnecessary re-renders. It returns a memoized callback.‬

‭const memoizedCallback = useCallback(() => {‬

‭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.‬

‭const inputRef = useRef(null);‬

‭ 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.‬

You might also like