React Concepts Custom Hooks and React Window - Monica AI Chat
React Concepts Custom Hooks and React Window - Monica AI Chat
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
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.

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>
);
};
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.

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

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.
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.
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.
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
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
Use Cases
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:
7. Memory Leaks
Memory leaks occur when references to unused objects are retained, causing
performance issues.
Common Causes
Uncleared timers.
Active subscriptions.
Solutions
Cleanup in useEffect .
8. Tree Shaking
Tree shaking eliminates dead code, reducing bundle sizes. ES6 imports facilitate
static analysis for unused code removal.
Example
javascript Copy
9. Garbage Collection
JavaScript's garbage collector automatically reclaims memory from objects no
longer in use.
Example
javascript Copy
12. React.lazy
React.lazy enables code splitting, loading components only when needed.
Example
javascript Copy
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
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.
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.
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
Use Cases
Rendering large datasets.
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:
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.
Solutions
Cleanup in useEffect .
8. Tree Shaking
Tree shaking eliminates dead code, reducing bundle sizes. ES6 imports facilitate
static analysis for unused code removal.
Example
javascript Copy
9. Garbage Collection
JavaScript's garbage collector automatically reclaims memory from objects no
longer in use.
Example
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:
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.
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
Use Cases
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