0% found this document useful (0 votes)
14 views32 pages

React Concepts Custom Hooks and React Window - Monica AI Chat

The document covers various advanced concepts in React, including the use of React Window for efficient rendering, the importance of using state and props over direct variables, and techniques for caching data. It also discusses memory leaks, tree shaking, garbage collection, and async/await for handling asynchronous operations. Additionally, it highlights the use of React.lazy for code splitting and implementing infinite scroll in applications.

Uploaded by

noxiousrocco
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)
14 views32 pages

React Concepts Custom Hooks and React Window - Monica AI Chat

The document covers various advanced concepts in React, including the use of React Window for efficient rendering, the importance of using state and props over direct variables, and techniques for caching data. It also discusses memory leaks, tree shaking, garbage collection, and async/await for handling asynchronous operations. Additionally, it highlights the use of React.lazy for code splitting and implementing infinite scroll in applications.

Uploaded by

noxiousrocco
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
You are on page 1/ 32

Custom hooks

Diffrent types of loops


2.React.window
React.Window is often a reference to using the React Window
library, which is designed for efficiently rendering large lists and
tabular data in React applications. It provides a virtualized
approach, meaning it only renders the items currently visible in the
viewport, which greatly improves performance for long lists.
Key Features of React Window:
* Performance: Only renders the visible items, reducing the number
of DOM nodes created.
* Flexibility: Supports both lists and grids, making it versatile for
various use cases.
* Simplicity: Easy to integrate with existing React applications.
*
*
Use Cases:
* Rendering large datasets in tables or lists.
* Improving performance for scrollable components.
* Efficiently handling dynamic content.

3.Why we are not using direct variables in react


using state and props instead of direct variables is essential for
several reasons:
1. Reactivity
React's core feature is its ability to react to changes. When you
use state (via useState or class components' state), React
automatically re-renders components when that state
changes. Direct variables do not trigger re-renders, which can lead
to inconsistencies in the UI.
2. Component Lifecycle
State variables are tied to the component lifecycle. When state
changes, React knows when to re-render and update the DOM.
Direct variables do not have this connection, making it harder to
manage updates and lifecycle events.
3. Encapsulation
Using state helps encapsulate the data specific to a
component. This encapsulation promotes better organization and
separation of concerns, making your code easier to understand
and maintain.
4. Predictability
State management through React’s built-in hooks (like
useState, useReducer, etc.) provides a predictable flow for data
changes. This predictability is crucial for debugging and
maintaining applications, especially as they grow in complexity.
5. Performance Optimization
React optimizes rendering by only re-rendering components
that depend on changed state or props. Direct variables could lead
to unnecessary re-renders or stale UI if they are not correctly
managed.
6. Integration with React Features
Many React features (like hooks, context, and effects) rely on
state and props. For instance, hooks like useEffect depend on state
changes to trigger side effects, which wouldn’t work correctly with
direct variables.

4.Cookies
Cookies are a common way to store and retrieve data on the
client side in web applications. Cookies can be used to store
information such as user preferences, session data and
other data that needs to persist across different sessions or pages.
Though cookies can be managed in JavaScript through custom
means, using a well-maintained third-party library to manage
cookies can help ensure browser compatibility, provide
built-in security features, and save us time. Many different popular
JavaScript libraries exist when it comes to handling cookies
which include js-cookie, universal-cookie and react-cookie.
js-cookie — Cookies.set('language', language),
Cookies.get("language”), Cookies.remove('language’),
5.Storage apis
The Storage interface of the Web Storage API provides access
to a particular domain's session or local storage. It allows, for
example, the addition, modification, or deletion of stored
data items. To manipulate, for instance, the session storage for a
domain, a call to Window.sessionStorage is made; whereas
for local storage the call is made to Window.localStorage.
6.Caching works
Caching in React can enhance performance by reducing the
need to fetch data repeatedly and minimizing unnecessary renders.
Here are several strategies and techniques to
implement caching effectively in a React application:
1. State Management Libraries — Libraries like Redux or
Zustand can help manage application state and cache data. They
can store fetched data in a global state, so subsequent
components can access it without refetching.
2. React Query — React Query is a powerful library for
fetching, caching, and syncing server state in React applications. It
automatically caches results based on keys, and you can easily
manage stale data.
3. Local Storage or Session Storage— For persisting data
across sessions, you can use localStorage or sessionStorage. This
method is useful for caching data that doesn't change often.
4. Memoization — Using React's built-in useMemo and
useCallback hooks can help cache computations or functions that
are expensive to recreate, thus preventing unnecessary renders
5. Service Workers —Implementing service workers can cache
network requests, allowing offline access and faster load times.
Libraries like Workbox can simplify this process.
7.Memory leaks and its cure
Memory leaks in React can lead to performance issues and
crashes, especially in larger applications. A memory leak occurs
when the application retains references to objects that are no
longer needed, preventing the garbage collector from reclaiming
that memory.
Common Causes of Memory Leaks in React
1.Event Listeners — Not cleaning up event listeners in
components can lead to memory leaks, as the listeners hold
references to the component.
2.Timers and Intervals — Not clearing timers or intervals when
a component unmounts can keep the component alive longer than
necessary.
3.Subscriptions — Leaving subscriptions active (like
WebSocket or observable subscriptions) without cleanup can also
cause leaks.
4.State Updates on Unmounted Components — Attempting to
update the state of a component after it has unmounted can lead
to memory leaks.
How to Cure Memory Leaks in React —
1.Cleanup in useEffect — When using the useEffect hook,
always return a cleanup function to clear up any resources or
subscriptions.
useEffect(() => { const timer = setInterval(() => { //
some action }, 1000); return () => clearInterval(timer); // Cleanup },
[]);
2.Remove Event Listeners — If you add event listeners, make
sure to remove them in the cleanup function.
useEffect(() => { const handleResize = () => { // handle
resize }; window.addEventListener('resize', handleResize); return ()
=> { window.removeEventListener('resize',
handleResize); // Cleanup }; }, []);
3.Manage Subscriptions — if you're using any subscriptions
(like WebSockets), make sure to unsubscribe when the component
unmounts.
useEffect(() => { const subscription =
someAPI.subscribe(data => { // handle incoming data }); return ()
=> { subscription.unsubscribe(); // Cleanup }; }, []);
4. Avoid State Updates on Unmounted Components — To
prevent state updates on unmounted components, you can use a
flag to track whether the component is still mounted.
const MyComponent = () => { const [data, setData] =
useState(null); const isMounted = useRef(true); useEffect(() => {
fetchData().then(fetchedData => { if (isMounted.current) {
setData(fetchedData); } }); return () => { isMounted.current = false;
// Mark as unmounted }; }, []); return <div>{data}</div>; };
5.Profiling and Debugging — Use React's built-in Profiler and
tools like Chrome DevTools to monitor memory usage and detect
potential leaks. The Profiler can help identify components that are
rendering too often or not cleaning up correctly.

8.Tree shaking
Tree-shaking is a concept in frontend development that
involves the elimination of dead code or unused code.
Tree-shaking has become quite popular in modern web
development due to the rise of ES6 import and export statements,
which help with static analysis of JavaScript files. This basically
means that, at compile time, the compiler can determine imports
and exports and programmatically decide which code should
be executed, as opposed to Common JS and AMD modules, which
are both analyzed dynamically. Examples of both ES6 imports and
CommonJS imports are shown below where the size bundle of
ES6 imports is drastically reduced as opposed to using CommonJS
modules for importing packages.
// CommonJS example of importing a package. The entire
package is imported const lodash = require('lodash'); 70.7K
(gzipped: 24.7k)
// ES2015(ES6) Sample of importing a specific dependency
with tree shaking import isArray from 'lodash/isArray' 1K (gzipped:
505)
Why do We Need Tree-Shaking?
The concept of tree-shaking is really important when it comes
to building an optimized codebase because it can significantly
reduce the bundle size of the application that is being
developed. The dependencies we installed in our application can
result in a laggy performance for our applications. The reason is
because most of the packages we install really don’t need all of
their dependencies and this results in importing large bundles
where we end up needing just a small part of the bundle. A
typical example is the lodash package like the example above,
where you only need to import one of its dependencies, and
then, instead of having to install the entire lodash package, we only
import a fraction of it.
Tree-Shaking in React with Different Bundlers: webpack and
Rollup — Having to implement tree-shaking with React will require
you to have a module bundler that will bundle the entire
codebase. A useful example for achieving this task is using either
webpack or Rollup for bundling your application.
webpack — webpack is a JavaScript module bundler and its
main purpose is to bundle JavaScript files for usage in the browser.
webpack supports tree- shaking, but a bit of concern with this
support is that webpack uses the babel-preset-env package, which
bundles your files and transforms the files back to CommonJS
module. Because CommonJS is not statically typed, that means
tree-shaking the bundles will become difficult.
—In order to achieve tree-shaking while bundling the
application, there are some configurations that will be required to
enable tree-shaking with webpack, shown below.

Rollup
Rollup is a module bundler for JavaScript that compiles small
pieces of code into something larger and more complex, such as a
library or application. Rollup also statically analyzes the
code you are importing and will exclude anything that isn’t actually
used. This allows you to build on top of existing tools and modules
without adding extra dependencies or bloating the size of your
project.

9.Garbage collector
Garbage collection in JavaScript is an automatic memory
management feature that helps reclaim memory occupied by
objects that are no longer in use, preventing memory leaks and
optimizing performance. Here’s an overview of how it works
10.Async and await
async and await are part of JavaScript's asynchronous
programming model, introduced in ES2017 (ES8). They are used to
work with Promises in a more readable and cleaner way,
simplifying asynchronous code that would otherwise use .then() and
.catch() for promise handling.
async function: A function that is declared with the async
keyword. This automatically makes it return a Promise, and you can
use await inside it.
await expression: Pauses the execution of an async function
until a Promise is resolved. It can only be used inside an async
function.
async function myAsyncFunction() {
// Code here runs synchronously
const result = await someAsyncTask();
console.log(result);
}
1.Async functions always return a Promise.
* If the return value is not explicitly a promise, JavaScript will
wrap it in a resolved promise.
* If an error is thrown inside an async function, the returned
promise will be rejected with that error.
* 2. Await pauses the execution of the async function.
* await can only be used inside an async function.
* When the await expression is encountered, JavaScript waits
for the Promise to resolve or reject before moving to the next line
of code.

Handling Errors with try/catch —

Parallel Execution with Promise.all
Sometimes you need to execute multiple async tasks in parallel.
You can do this using Promise.all(), which allows multiple promises
to run concurrently.


Benefits of async/await — Cleaner code, Error handling, Control
flow: You can easily sequence asynchronous operations with await,
or run them in parallel with Promise.all()
—— await only works with Promises , Not using await in an async
function

11. Async and defer

Feature async defer


Download behavior Downloads the script asynchronously.
Downloads the script asynchronously.
Execution timing Executes as soon as the script is available (could
be before or after the DOM is parsed). Executes after the HTML is
fully parsed, in order of appearance.
Order of execution Execution order not guaranteed (based on
download order). Execution order is guaranteed (in order of
appearance).
Best for Independent scripts that don’t rely on other scripts or
DOM. Scripts that depend on the DOM being fully loaded or
other scripts.
Impact on page render May block rendering if the script takes too
long to download. Does not block rendering (non-blocking).

12. React.lazy
React.lazy() is a function that enables code splitting in React.
Code splitting allows you to split your JavaScript bundle into
smaller chunks, so you only load the code needed for the current
view or page. This can significantly improve the performance of
your React app by reducing the initial load time.
What Does React.lazy() Do?
React.lazy() enables dynamic imports for components, meaning you
can load them only when they are needed (i.e., when the
component is rendered). When the component is required for the
first time, React will download the code for that component
asynchronously, improving your app's startup time.
— React.lazy() works only with default exports, and it must be used
with Suspense, a component that allows you to specify loading
behavior for your lazily-loaded components.
const MyComponent = React.lazy(() =>
import('./MyComponent')); React.lazy() takes a function that returns
a Promise (usually from import()), which resolves to a module
containing the component to be loaded lazily.

React.lazy() is used to lazily load AboutPage and HomePage. Both


components will only be loaded when their respective routes are
visited.
Suspense is used to handle the loading state while the lazily-loaded
components are being fetched. In this example, we're using a
simple <div>Loading...</div> as the fallback.
Suspense wraps the parts of your app where lazy-loaded
components are used. You can wrap individual routes, parts of the
UI, or the whole app, depending on your use case.

USE — You want to split your JavaScript bundle to improve the


initial loading time.
You have components that are not needed immediately on
page load (e.g., components used in certain routes, modals, or
dropdowns).
You want to load larger components only when the user
navigates to a specific part of the app (e.g., different routes in a
single-page app).

13. Infinite scroll


1. Infinite scroll is a technique where the content of a page is
loaded incrementally as the user scrolls, instead of loading all the
content at once. It’s commonly used in social media feeds, image
galleries, and long lists of items to provide a smooth user
experience.

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


// Dummy API URL for fetching data (you can replace this with your
actual API)
const API_URL = 'https://jsonplaceholder.typicode.com/posts';

const InfiniteScroll = () => {


const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);

// Function to fetch posts


const fetchPosts = async () => {
setLoading(true);
const res = await fetch(${API_URL}?_page=${page}&_limit=10);
const newPosts = await res.json();
setPosts(prevPosts => [...prevPosts, ...newPosts]);
setLoading(false);
};

// Load posts on component mount and when page changes


useEffect(() => {
fetchPosts();
}, [page]);

// Handle scroll event


const handleScroll = useCallback(() => {
const bottom = document.documentElement.scrollHeight ===
document.documentElement.scrollTop + window.innerHeight;
if (bottom && !loading) {
setPage(prevPage => prevPage + 1);
}
}, [loading]);

useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [handleScroll]);

return (
<div>
<h1>Infinite Scroll Example</h1>
<div style={{ minHeight: '200px' }}>
{posts.map(post => (
<div key={post.id} style={{ padding: '20px', border: '1px solid
#ccc', marginBottom: '10px' }}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
</div>
{loading && <div>Loading...</div>}
</div>
);
};

export default InfiniteScroll;

14. Stopwatch

15. Memoizations
* Memoization is an optimization technique used to improve the
performance of a function by caching its results based on its inputs.
In the context of React, memoization is often used to prevent
unnecessary re-renders of components or recalculations of
expensive computations when their inputs haven't changed. This
can be especially useful in large applications with complex
components or lists.
In React, memoization can be applied using the following hooks
and utilities:
React.memo(): A higher-order component (HOC) used to prevent
re-renders of a component when its props have not changed.
useMemo(): A React hook used to memoize expensive calculations
inside functional components.
useCallback(): A React hook used to memoize functions so that they
don't get recreated on every render.

React.memo()
React.memo() is a higher-order component that memoizes a
component, preventing it from re-rendering unless its props
change. It’s useful for functional components that render the same
output for the same set of props.

2. useMemo() Hook
useMemo() is used to memoize the result of a function that returns
a value. It is useful for optimizing expensive calculations or
transformations that don’t need to be recalculated on every render
if the dependencies haven’t changed.

3. useCallback() Hook
useCallback() is similar to useMemo(), but instead of memoizing a
value, it memoizes a function. This is useful when passing callbacks
down to child components, especially when those child
components are wrapped with React.memo() to avoid unnecessary
re-renders.

Optimisations in react
React is a highly efficient library, but as your application
grows in size and complexity, performance can start to degrade,
particularly with large component trees, frequent updates, and
expensive rendering. To improve performance, React provides
various built-in optimizations and techniques that you can leverage.
1. Avoiding Unnecessary Re-renders
React re-renders components whenever their state or props
change. However, not all state or props changes require a full re-
render of a component. You can optimize re-renders by:
ex- React.memo() for Functional Components ,
shouldComponentUpdate for Class Components
2. Memoizing Expensive Calculations
When you have computations that are expensive to re-
calculate on each render (e.g., complex algorithms, filtering large
lists), you can use memoization to store and re-use results.

3. Optimizing List Rendering
Rendering large lists or tables can be a performance
bottleneck. You can optimize list rendering by limiting the number
of components that are rendered at once.

When to use: Use virtualization for long lists, tables, or grids where
only a small number of items are visible at any given time.
4. Lazy Loading and Code Splitting
Lazy loading helps improve the initial load time of your application
by splitting the code into smaller chunks and only loading them
when necessary.
a) React.lazy()
b) Code-Splitting with React Router
5. Batching State Updates
React batches state updates within event handlers, but in
certain situations (like asynchronous code, setTimeout(), or
setInterval()), updates may not be batched. You can explicitly batch
updates to reduce the number of re-renders.
a) React 18's Automatic Batching
React 18 introduces automatic batching, which automatically
batches state updates in asynchronous functions (e.g., inside
setTimeout, setInterval, etc.).

When to use: Rely on React’s automatic batching to reduce the
number of renders. Make sure you’re using React 18+ for automatic
batching in asynchronous code.

Error boundaries
Suspence
Context provider setup
Debouncing
Input elements that trigger state updates on every keystroke (like
search input) can cause performance problems due to frequent
renders. You can debounce or throttle these updates to minimize
the number of state changes.

When to use: Use debouncing when you need to delay the update,
such as for search bars, filters, or other real-time input-based UI
elements.
Throttling— For cases where you want to limit the number of
updates (e.g., limiting the number of scroll or resize events),
throttling can help.

Avoid Inline Functions in JSX


Inline functions can lead to unnecessary re-renders, especially
when passed as props to child components. Always define functions
outside of the render method to avoid creating new function
instances on each render.
// Bad <MyComponent onClick={() => doSomething()} />
// Good const handleClick = () => { doSomething(); };
<MyComponent onClick={handleClick} />

Object flattening different variants


Flattening an object refers to transforming a nested object (with
properties containing other objects) into a single-level object,
where nested keys are concatenated with a separator, typically a
dot (.). Flattening can be useful when dealing with complex data
structures, especially when preparing data for storage or APIs, or
when working with certain libraries that expect flat structures.
1. Simple Object Flattening (Single Level of Nesting)

Closures concept n variant problem


A closure in JavaScript is a function that "remembers" its lexical
scope, even when the function is executed outside that scope. In
simpler terms, closures allow a function to access variables from its
outer (enclosing) function even after the outer function has finished
executing.
A closure is created when:
1. A function is defined inside another function.
2. The inner function accesses variables from the outer function.
Key Characteristics of Closures:
1. Lexical Scoping: The scope of a variable is determined by where it
is defined in the source code, not where it is executed.
2. Encapsulation: Closures can "enclose" variables, allowing you to
create private data that cannot be directly accessed from outside
the closure.
3. Persistence of Variables: The inner function retains access to the
variables in the outer function’s scope even after the outer function
has returned.

Explanation:
* outerFunction defines a variable outerVar and returns the
innerFunction.
* innerFunction is a closure because it accesses outerVar even after
outerFunction has finished executing.
* The closure retains access to outerVar after the outerFunction has
returned.

Variants of Closure Problems


1.Basic Closure Problem: Accessing Variables from Outer Scope

2.Closure with Looping (Common Problem)
One of the most common mistakes with closures involves the use of
closures inside loops. Since closures capture variables by reference,
they often result in unexpected behavior when used inside a loop.

The use of let ensures that each iteration of the loop has its own
separate scope for i. This results in the closure retaining the correct
value of i for each function.
Problem: Using var Inside Loops (Common Pitfall)

* When you use var, the variable i is not scoped to the loop but to
the function, so all closures created inside the loop refer to the
same i variable, which ends up being 3 after the loop finishes. This
is a common pitfall when using var in closures inside loops.
Solution: Use let instead of var to create block-scoped variables
inside loops.

Function currying
Function currying is a technique in functional programming
where a function that takes multiple arguments is transformed into
a series of functions, each taking one argument. In other words,
currying breaks down a function that takes multiple parameters into
a series of unary (single-argument) functions.
Why Use Currying?
1. Partial Application: Currying allows you to create specialized
versions of functions by pre-setting some of the arguments. This
can simplify code when you often use the same parameters.
2. Reusability: Currying helps in creating reusable functions that can
be composed and combined in a modular way.
3. Functional Programming: Currying is commonly used in
functional programming paradigms where functions are treated as
first-class citizens, enabling more flexible and composable
functions.

Strict mode concept


Strict Mode in JavaScript is a way to opt into a restricted
variant of JavaScript, where certain behaviors that are generally
considered bad practice or prone to errors are disallowed. It was
introduced in ECMAScript 5 (ES5) to make JavaScript more secure,
performant, and easier to maintain by catching common coding
mistakes early. —————— ("use strict";)
Features of Strict Mode—
1. Eliminates this Coercion
// Non-strict mode: this is the global object, in strict mode: this
is `undefined
2. Disallows delete on Non-Configurable Properties
In strict mode, attempting to delete variables, functions, or
object properties that are non-configurable will throw an error. In
non-strict mode, delete would silently fail.

3. Prevents Using Undeclared Variables

4. Disallows Duplicate Parameter Names


function myFunction(a, a) { // SyntaxError: Duplicate parameter
name not allowed in this context
5. No with Statements
Advantages of Strict Mode — Fewer Errors, Security, Cleaner Code,
Performance Optimization

Polyfill for all promises and all polyfills

React 18 features
Feature Description
Concurrent Rendering Introduced as an opt-in feature to improve
UI responsiveness.
Automatic Batching Updates triggered by event handlers and
promises are batched automatically.
Suspense for Data Fetching Suspense now supports data fetching
and async components.
useTransition Hook Mark updates as non-urgent, allowing React to
prioritize more important work.
useDeferredValue Hook Delay non-urgent updates to improve user
experience.
Concurrent SSR Improved server-side rendering with streaming
and Suspense support.
startTransition API Used outside components to mark certain
updates as non-urgent.
Strict Mode Enhancements Helps detect side effects and
potential issues with Concurrent Mode.

Class concpet in react


Lifecycle Methods in Class Components
a. Mounting Lifecycle Methods — These methods are called when
the component is created (i.e., inserted into the DOM).
constructor(props): Called before the component is mounted.
Used for initializing state and binding event handlers.
componentDidMount(): Called immediately after the
component is mounted in the DOM. This is a good place for
asynchronous operations like data fetching
componentDidMount() is called after the component has been
mounted. In this example, we simulate fetching user data from an
API and updating the state once the data is fetched.
b. Updating Lifecycle Methods: These methods are called when the
component is being updated due to changes in props or state.
* shouldComponentUpdate(nextProps, nextState): Determines
whether the component should re-render. Returns a boolean value.
By default, returns true.
* componentDidUpdate(prevProps, prevState): Called after the
component has re-rendered due to changes in props or state.
* getDerivedStateFromProps(nextProps, nextState): Called before
every render, whether from props or state changes. It is used for
updating the state in response to prop changes.
* componentDidUpdate() is used here to log when the count has
been updated.
c. Unmounting Lifecycle Method: This method is called when the
component is about to be removed from the DOM.
* componentWillUnmount(): Used for cleanup operations such as
clearing timers, cancelling network requests, or removing event
listeners.
* componentWillUnmount() clears the interval when the Timer
component is about to be unmounted from the DOM, preventing
memory leaks.
Feature Class Components Functional Components
Syntax ES6 classes, extends React.Component Function that
returns JSX
State Management this.state, this.setState useState hook
Lifecycle Methods componentDidMount, componentWillUnmount,
etc. useEffect hook
Performance Higher overhead, larger bundle size More
lightweight, often faster
Simpler Syntax Verbose, especially for handlers More
concise and easier to read
Hooks Support Not supported Fully supported (since React
16.8)

React fibre
React Fiber is the reimplementation of React's core algorithm,
designed to improve the performance of React applications. It was
introduced in React 16 (released in 2017) to address some
limitations in the previous React reconciliation algorithm (referred
to as "Stack Reconciliation"). Fiber enables more flexible, efficient,
and smoother updates to the UI, especially for complex, large-scale
applications.
In simple terms, React Fiber is an overhaul of React's rendering
engine, enabling features like asynchronous rendering, prioritization
of updates, and smoother transitions for animations and interactive
components.
Key Features and Benefits of React Fiber
1.Asynchronous Rendering —
Old Approach: React previously used a synchronous rendering
approach, meaning when React performed updates to the DOM, it
blocked the main thread until the update was complete.
Fiber's Approach: Fiber introduces asynchronous rendering,
allowing React to split rendering work into chunks and pause or
resume rendering based on the priority of tasks. This helps prevent
the UI from freezing during heavy updates, keeping the app
responsive.
2.Prioritization of Updates
* React Fiber allows for priority-based rendering, which means more
important updates (like user interactions) can be processed first,
while less critical updates (such as background tasks) can be
deferred.
* React uses a priority system to assign importance to different
types of updates:
* High Priority: Immediate user interactions (clicks, typing).
* Low Priority: Background tasks (like rendering off-screen
content or non-essential updates).
* Fiber allows React to interrupt rendering when necessary and give
precedence to higher-priority tasks.
3.Incremental Rendering
* Fiber introduces incremental rendering, meaning React can break
the work into smaller chunks and spread it out over time, thus
avoiding long-blocking operations and improving UI
responsiveness.
4.Concurrent Rendering (Experimental)
* Fiber made it easier for React to implement concurrent rendering
(still in development as of React 18+), which is a set of features
allowing React to prepare multiple versions of the UI at the same
time. This helps in rendering updates in the background without
blocking the main thread.
* Features like Suspense and Concurrent Mode are built on top of
Fiber to enable features like lazy loading and async rendering of
components.

CSR VS SSR all details


Feature CSR (Client-Side Rendering) SSR (Server-Side Rendering)
Rendering Location Rendering happens in the browser (client-side).
Rendering happens on the server (server-side).
Initial Load Speed Slower initial load, since JavaScript needs to
load and execute. Faster initial load, since HTML is pre-rendered
by the server.
User Experience Smooth transitions after the first load; fast
navigation between pages. Can be slower on subsequent
navigations; full-page reload.
SEO SEO may be harder since content is rendered dynamically by
JavaScript. SEO is better since the content is fully rendered on
the server.
Performance Can be slow on low-powered devices due to large
JavaScript bundles. Faster performance on low-end devices since
HTML is already rendered.
Complexity Less server-side complexity, but more client-side
JavaScript. More server-side complexity, but less client-side
JavaScript.
Caching Caching is typically done on the client-side (browser
cache). Caching can be done on the server, using various
strategies (e.g., static rendering, CDN).
Interactivity High interactivity (SPAs can run without page
reloads). Limited interactivity until JavaScript hydrates the page.
Use Cases SPAs (Single-Page Applications), dashboards,
dynamic sites. Static sites, blogs, e-commerce sites, news sites.

Why we are using context provider over prop drilling


prop drilling is a valid technique, it can become cumbersome and
inefficient as your application grows. Context Provider, on the other
hand, offers a more elegant solution for managing state across
deeply nested components
Aspect Prop Drilling Context Provider
Data Passing Passing data from parent to child components,
possibly through many layers. Providing data to deeply nested
components without passing through each layer.
Code Complexity Increases with more nested components.
Simplifies the code by allowing global state access.
Performance Can lead to excessive re-renders as props change.
Potential for re-renders on every context change, but can be
optimized.
Maintainability Harder to maintain as the app grows. Easier
to maintain and scale in larger applications.
Reusability Components are tightly coupled. More decoupled
components, as they can access data without relying on prop
chains.
Use Cases Small or shallow component trees. Sharing global or
cross-cutting state like authentication, themes, language
preferences, etc.
Why we using redux inplace of context provider.

Both Redux and the React Context API are popular tools used for
managing application state in React. However, while they share
some similarities, they have distinct purposes and use cases. In
certain scenarios, Redux might be a better choice than the Context
API for managing global state.

1. Performance Concerns
Context API Performance: The Context API can trigger a re-render
of all components that consume the context whenever the context
value changes. This can lead to performance bottlenecks, especially
in large applications where state changes frequently. Even if only a
small part of the state changes, every consumer of the context will
re-render.
Redux Performance: Redux, on the other hand, is optimized for
large-scale state management. It uses the "one-way data flow"
pattern and reducer functions to ensure that only the components
subscribed to specific slices of the state are re-rendered when those
parts of the state change. Redux also provides tools like Redux
DevTools and middleware (e.g., redux-thunk, redux-saga) that help
manage complex asynchronous flows efficiently.

When Redux shines:


* When you have frequent updates to global state, and you need to
minimize unnecessary re-renders.
* When your application has a large number of components that
need to consume the state.
* When your state management involves complex logic, actions,
and middleware, like handling side effects (e.g., making API calls).

2. Complex State Logic and Side Effects


Redux allows you to manage complex state through reducers and
actions. It also supports middleware like redux-thunk, redux-saga,
or redux- observable to handle asynchronous tasks or side effects
in a structured way. This is ideal for dealing with scenarios like API
requests, form validation, or updating the state based on complex
logic.

Context API is more limited when it comes to handling complex


side effects. While you can manage simple state with Context,
handling things like async actions or managing multiple related
state pieces with Context is more difficult and often leads to the
need for external solutions.

When Redux shines:


* When you need to manage complex asynchronous workflows
(e.g., fetching data, form submissions).
* When the state depends on multiple actions or side effects that
need to be handled in a clear and predictable way.
3. Scaling to Larger Applications.
* Redux provides a more scalable way to manage state. With Redux,
the state is centralized in a single store, and you can manage
different parts of your application’s state in separate reducers. This
makes it easier to maintain and scale your application as it grows,
without needing to manually manage and pass down contexts at
each level.
* Context API works well for small to medium-sized applications
where only a small subset of state needs to be passed around. As
the application scales, managing many context providers can make
the component tree messy and harder to maintain.
When Redux shines:
* When your application grows large and requires scalable state
management.
* When you need to centralize all state in a single store and
separate logic using reducers.

When to Use Context API Over Redux?


While Redux has many advantages in large applications, the React
Context API can still be a great choice for certain scenarios:
* Simple applications where you need to share global state across a
small to medium-sized component tree.
* Non-complex state management that doesn’t require heavy
asynchronous logic, side effects, or extensive middleware.
* Minimal global state needs (e.g., user authentication status, UI
themes, language preferences).
* If you're working on a small app or a prototype where you don't
need to manage state on a large scale.
Feature Redux Context API
Performance Optimized for large apps with frequent state updates
and complex data flows. Can cause unnecessary re-renders in large
apps, especially if state changes often.
State Management Centralized, predictable state with actions and
reducers. State is passed down through context providers, with no
standardized pattern.
Complexity More setup and boilerplate, but better for large,
complex apps. Simple and easy for small to medium apps.
Side Effects Handles async operations and side effects with
middleware (e.g., redux-thunk, redux-saga). No built-in support for
side effects or async operations.
DevTools Includes Redux DevTools for debugging and inspecting
state changes. No native debugging tools for tracking state
changes.
Scaling Scales well for large applications. May become harder to
manage with deeply nested components in large apps.

Jwt authentication—
Grid layout
CSS Grid Layout is a two-dimensional layout system for the web. It
allows you to design complex web page layouts with rows and
columns, offering a powerful way to create responsive, grid-based
layouts. Unlike Flexbox, which is a one-dimensional layout model,
CSS Grid allows you to manage both rows and columns at the same
time.

Themes implementation

HOC in react

Graph ql and rest mechanism

React vs angular
Feature React Angular
Type Library Framework
Developer Facebook Google
Learning Curve Steeper for beginners (JSX, Babel, Webpack)
Steeper (TypeScript, RxJS, CLI)
Architecture Component-based, unidirectional data flow MVC,
two-way data binding, opinionated
State Management React Context, Redux, MobX, Recoil
Services, NgRx, RxJS
Performance Virtual DOM Real DOM, change detection
Language JavaScript (JSX syntax) TypeScript (JavaScript
superset)
Community and Ecosystem Larger community, React Native for
mobile Enterprise-focused, large-scale applications
Tooling Webpack, Babel, Jest, React Developer Tools Angular CLI,
Jasmine, Karma, Protractor
Monica
Use Cases SPAs, dynamic UIs, web and mobile (React Native)
React Enterprise
Concepts Overview
applications, large-scale SPAs

1. Custom Hooks
Monolithic vs microfrontend vs mono repo
Custom hooks
Redux
in flow
React allow you to encapsulate logic and state management to
be reused across components. They help keep components clean and focused
on rendering.
Can you structure this and give me a document file also explain the
2. React Window
topics which are left unexplained.

React Window is a library for efficiently rendering large lists and tables in React
applications using virtualization.

Key Features

Performance: Only renders visible items, reducing DOM nodes.

Flexibility: Supports lists and grids.

Simplicity: Easy integration with existing apps.

Use Cases

Rendering large datasets.

Improving performance for scrollable components.

Handling dynamic content efficiently.

3. Using State and Props


Using state and props instead of direct variables is essential for:

1. Reactivity: Automatically triggers re-renders on state changes.

2. Component Lifecycle: Tied to lifecycle events for proper updates.

3. Encapsulation: Organizes component-specific data.

4. Predictability: Provides a clear data flow for debugging.

5. Performance Optimization: Minimizes unnecessary re-renders.

6. Integration with React Features: Works with hooks and context.

4. Cookies
Cookies are used for client-side data storage. They can store user preferences,
session data, etc. Libraries like js-cookie simplify cookie management.

Example
javascript Copy

Cookies.set('language', language);
Cookies.get('language');
Cookies.remove('language');

5. Storage APIs
The Web Storage API provides access to session and local storage for data
manipulation.

6. Caching in React
Caching enhances performance by reducing data fetching. Strategies include:

1. State Management Libraries: Use Redux or Zustand.

2. React Query: Caches and syncs server state.

3. Local/Session Storage: For persistent data.

4. Memoization: Use useMemo and useCallback .

5. Service Workers: For caching network requests.

7. Memory Leaks
Memory leaks occur when references to unused objects are retained, causing
performance issues.

Common Causes

Uncleaned event listeners.

Uncleared timers.

Active subscriptions.

State updates on unmounted components.

Solutions

Cleanup in useEffect .

Remove event listeners.

Manage subscriptions properly.

Avoid state updates on unmounted components.

8. Tree Shaking
Tree shaking eliminates dead code, reducing bundle sizes. ES6 imports facilitate
static analysis for unused code removal.

Example
javascript Copy

import isArray from 'lodash/isArray'; // Only imports what's needed

9. Garbage Collection
JavaScript's garbage collector automatically reclaims memory from objects no
longer in use.

10. Async and Await


Introduced in ES2017, async and await simplify promise handling.

Example
javascript Copy

async function myAsyncFunction() {


const result = await someAsyncTask();
console.log(result);
}

11. Async and Defer


Async: Downloads scripts asynchronously; execution timing is not
guaranteed.

Defer: Downloads scripts asynchronously; executes after HTML parsing.

12. React.lazy
React.lazy enables code splitting, loading components only when needed.

Example
javascript Copy

const MyComponent = React.lazy(() => import('./MyComponent'));

13. Infinite Scroll


Infinite scroll loads content as the user scrolls.

Example Implementation
javascript Copy

useEffect(() => {
fetchPosts();
}, [page]);
const handleScroll = useCallback(() => {
const bottom = document.documentElement.scrollHeight ===
document.documentElement.scrollTop + window.innerHeight;
if (bottom && !loading) {
setPage(prevPage => prevPage + 1);
}
}, [loading]);

14. Stopwatch
A simple stopwatch can be implemented using state to track time.

15. Memoization
Memoization caches results to prevent unnecessary re-renders.

Techniques

React.memo(): Prevents re-renders for unchanged props.

useMemo(): Memoizes expensive calculations.

useCallback(): Memoizes functions to avoid recreation.

16. Optimizations in React


Avoiding Unnecessary Re-renders: Use React.memo() and
shouldComponentUpdate .

Memoizing Expensive Calculations: Use useMemo() .

Optimizing List Rendering: Implement virtualization.

Lazy Loading: Use React.lazy() .

17. Error Boundaries


Error boundaries catch JavaScript errors in components and log them.

18. Context Provider vs. Prop Drilling


Using Context Provider simplifies state management across nested components,
avoiding cumbersome prop drilling.

19. Redux vs. Context API


Redux: Optimized for large apps with complex state logic and frequent
updates.

Context API: Suitable for simpler state management without complex logic.
20. JWT Authentication
JWT (JSON Web Tokens) are used for secure authentication in web applications.

21. CSS Grid Layout


CSS Grid allows for responsive, grid-based layouts, managing both rows and
columns.

22. Higher-Order Components (HOC)


HOCs are functions that take a component and return a new component,
enhancing functionality.

23. GraphQL vs. REST


GraphQL enables flexible data queries, while REST uses fixed endpoints.

24. React vs. Angular


Feature React Angular

Type Library Framework

Developer Facebook Google

Learning Curve Steeper for beginners Steeper

State Management Context, Redux Services, NgRx

Performance Virtual DOM Real DOM

25. Monolithic vs. Microfrontend vs. Monorepo


Monolithic: Single codebase for the entire application.

Microfrontend: Breaks the application into smaller, independent parts.

Monorepo: A single repository for multiple projects.

26. Redux Flow


Redux follows a unidirectional data flow, where actions are dispatched to
reducers that update the state.

This overview encapsulates various React concepts and practices, providing a


solid foundation for understanding and implementing
give methem in applications.
a document file of this
Monica

I can't create a document file directly, but I can provide you with the content
formatted for a document. You can copy this text into a word processor like
Microsoft Word or Google Docs and save it as a document file.

React Concepts Overview

1. Custom Hooks
Custom hooks in React allow you to encapsulate logic and state management to
be reused across components. They help keep components clean and focused
on rendering.

2. React Window
React Window is a library for efficiently rendering large lists and tables in React
applications using virtualization.

Key Features

Performance: Only renders visible items, reducing DOM nodes.

Flexibility: Supports lists and grids.

Simplicity: Easy integration with existing apps.

Use Cases
Rendering large datasets.

Improving performance for scrollable components.

Handling dynamic content efficiently.

3. Using State and Props


Using state and props instead of direct variables is essential for:

1. Reactivity: Automatically triggers re-renders on state changes.

2. Component Lifecycle: Tied to lifecycle events for proper updates.

3. Encapsulation: Organizes component-specific data.

4. Predictability: Provides a clear data flow for debugging.

5. Performance Optimization: Minimizes unnecessary re-renders.

6. Integration with React Features: Works with hooks and context.

4. Cookies
Cookies are used for client-side data storage. They can store user preferences,
session data, etc. Libraries like js-cookie simplify cookie management.

Example
javascript Copy

Cookies.set('language', language);
Cookies.get('language');
Cookies.remove('language');

5. Storage APIs
The Web Storage API provides access to session and local storage for data
manipulation.

6. Caching in React
Caching enhances performance by reducing data fetching. Strategies include:

1. State Management Libraries: Use Redux or Zustand.

2. React Query: Caches and syncs server state.

3. Local/Session Storage: For persistent data.

4. Memoization: Use useMemo and useCallback .

5. Service Workers: For caching network requests.

7. Memory Leaks
Memory leaks occur when references to unused objects are retained, causing
performance issues.

Common Causes
Uncleaned event listeners.

Uncleared timers.

Active subscriptions.

State updates on unmounted components.

Solutions
Cleanup in useEffect .

Remove event listeners.

Manage subscriptions properly.


Avoid state updates on unmounted components.

8. Tree Shaking
Tree shaking eliminates dead code, reducing bundle sizes. ES6 imports facilitate
static analysis for unused code removal.

Example
javascript Copy

import isArray from 'lodash/isArray'; // Only imports what's needed

9. Garbage Collection
JavaScript's garbage collector automatically reclaims memory from objects no
longer in use.

10. Async and Await


Introduced in ES2017, async and await simplify promise handling.

Example

give me pdf of this

Monica

I can't create a PDF directly, but I can guide you on how to do it. Here’s how you
can create a PDF from the content:

1. Copy the Content: Copy the text provided below.

2. Paste into a Document Editor: Open a document editor like Microsoft


Word, Google Docs, or any other text editor.

3. Format the Document: Ensure the format looks good (titles, headings, etc.).

4. Export as PDF:

In Microsoft Word: Go to File > Save As , then choose PDF from the
file type dropdown.

In Google Docs: Go to File > Download > PDF Document (.pdf) .

React Concepts Overview

1. Custom Hooks
Custom hooks in React allow you to encapsulate logic and state management to
be reused across components. They help keep components clean and focused
on rendering.

2. React Window
React Window is a library for efficiently rendering large lists and tables in React
applications using virtualization.

Key Features

Performance: Only renders visible items, reducing DOM nodes.

Flexibility: Supports lists and grids.

Simplicity: Easy integration with existing apps.

Use Cases

Rendering large datasets.

Improving performance for scrollable components.

Handling dynamic content efficiently.

3. Using State and Props


Using state and props instead of direct variables is essential for:

1. Reactivity: Automatically triggers re-renders on state changes.

2. Component Lifecycle: Tied to lifecycle events for proper updates.

3. Encapsulation: Organizes component-specific data.

4. Predictability: Provides a clear data flow for debugging.

5. Performance Optimization: Minimizes unnecessary re-renders.

6. Integration with React Features: Works with hooks and context.

4. Cookies
Cookies are used for client-side data storage. They can store user preferences,
session data, etc. Libraries like js-cookie simplify cookie management.

Example
javascript Copy

Cookies.set('language', language);
Cookies.get('language');
Cookies.remove('language');

5. Storage APIs
The Web Storage API provides access to session and local storage for data
manipulation.

6. Caching in React
Caching enhances performance by reducing data

You might also like