0% found this document useful (0 votes)
10 views26 pages

Advanced React

The document provides an in-depth exploration of advanced React concepts, focusing on the useReducer hook for complex state management and React Router for building single-page applications. It details the mechanics of routing, including the use of components like BrowserRouter, Routes, and Link, as well as performance optimization techniques such as memoization and code splitting. Additionally, it discusses the differences between the useReducer hook and Redux, along with best practices for using useEffect.

Uploaded by

lknvkllw
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)
10 views26 pages

Advanced React

The document provides an in-depth exploration of advanced React concepts, focusing on the useReducer hook for complex state management and React Router for building single-page applications. It details the mechanics of routing, including the use of components like BrowserRouter, Routes, and Link, as well as performance optimization techniques such as memoization and code splitting. Additionally, it discusses the differences between the useReducer hook and Redux, along with best practices for using useEffect.

Uploaded by

lknvkllw
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/ 26

Advanced React.

Js
Advanced Hooks
useReducer Hook
The useReducer() hook in React is similar to useState(), but is intended for
more complex state changes. In this article, we’ll be exploring how
useReducer() can be used to manage state differently than the standard
useState() hook.
When working with state in a React application, we often need to manage
state changes and updates in a way that can be easily understood and
maintained. This is where React’s useState() and useReducer() hooks come
in. These hooks provide us with tools to manage state in a functional
component, allowing us to avoid the need for complex class-based
component structures.
●​ Takes a reducer() function as the first argument. This reducer()
function is a pure function that takes in the current state, an action,
and returns a new state. It does not modify the original state, but
rather returns a new state based on the action passed to it.
●​ Takes an initial state value as the second argument.
●​ Takes an (optional) initializer function that can be used to initialize
state as the third argument.
●​ And returns an array containing the current state value and a
dispatch() function that can be used to trigger state changes by
dispatching actions to the reducer.
Why useReducer?

Managing State With useReducer:


How Reducer Updates the state:

useState vs useReducer
When to Use the useReducer hook?

REACT ROUTER: BUILDING SINGLE PAGE APPLICATIONS (SPA)


WHAT IS ROUTING?

What is SPA?
React Router
Install react router using npm i react-router-dom@latest (V6 in our case)
Defining our Routes in a Declarative Way:
BrowserRouter
●​ Purpose: BrowserRouter is a component that provides the routing
infrastructure for your application. It uses HTML5 history API
(history.pushState()) to keep your UI in sync with the URL.
●​ Usage: It should wrap all your <Route> components and be placed at
the top level of your application to enable routing.
Routes
●​ Purpose: Routes is a component used to define the routing
configuration of your application. It acts as a container for multiple
<Route> components.
●​ Usage: It serves as a parent component that holds all your route
definitions within the <BrowserRouter>.
Route
●​ Purpose: Route is used to define a mapping between a URL path and
a React component to render when the path matches the current URL.
●​ Usage: It specifies the path using the path prop and the component to
render using the element prop.
Linking Between Routes with <Link/> and <NavLink />
<Link> Component
●​ Purpose: <Link> is used to navigate between different routes defined
in your React application without causing a full page reload.
●​ Usage: It renders an anchor (<a>) tag in the DOM with an href attribute
set to the specified route path.
Key Points:
●​ Provides declarative navigation.
●​ Prevents full page refreshes.
●​ Useful for standard navigation within the application.
<NavLink> Component
●​ Purpose: <NavLink> is a specialized version of <Link> that allows
styling based on the current active route.
●​ Usage: It applies an active class (or any custom class specified via
activeClassName) when the route it links to matches the current URL.
Key Points:
●​ Provides additional visual feedback for the active route.
●​ Supports conditional styling based on route matching.
●​ Use exact prop with <NavLink to="/"> to match exact routes.
Nested Routes
Main Route (/app):
●​ The <Route> component with path="app" specifies that when the URL
matches /app, the <AppLayout /> component should be rendered.
Nested Routes (/app/cities, /app/countries, /app/form):
●​ Nested <Route> components inside <AppLayout> specify different
paths (cities, countries, form) relative to /app.
●​ These nested routes will render their respective components (<p>List
of Cities</p>, <p>Countries</p>, <p>Form</p>) inside <AppLayout>
when their paths match.
<Outlet> Component:
●​ Inside <AppLayout>, you would use the <Outlet> component to render
the nested routes defined in its child routes.
●​ The <Outlet> component acts as a placeholder where nested routes
will be rendered.
Index Route
<Route index element={...} />
●​ Purpose: Defines the default content or component to render when
the parent route matches its path exactly (i.e., when no nested route
paths match).
●​ Usage: Typically used within a parent <Route> component to provide a
default view or landing page for nested routes.
URL For State Management

In React Router v6, you can handle routing with both path parameters and
search parameters. This allows you to create dynamic routes and pass
additional query parameters through the URL. Here's an overview of how
this works:
Defining Routes with Path Parameters
Using path parameters, you can define dynamic segments in your routes.
For example:
import { BrowserRouter as Router, Routes, Route } from
'react-router-dom';​
import City from './City';​
export default function App (){ return (​
<Router>​
<Routes>​
<Route path="cities/:id" element={<City />} />​
</Routes>​
</Router>);
In this example, the :id part of the path is a placeholder for a dynamic
segment that will match any value and make it available to the City
component.
Creating Links with Search Parameters
You can create links that include both path parameters and search
parameters. For example:
import { Link } from 'react-router-dom';​
import styles from './styles.module.css';​

const CityItem = ({ id, position }) => (​
<Link​
to={`/cities/${id}?lat=${position.lat}&lng=${position.lng}`}​
className={styles.cityItem}​
>​
View City​
</Link>​
);​

export default CityItem;
In this example, the Link component generates a URL that includes the city
ID as a path parameter and the latitude and longitude as search
parameters.
Using useParams Hook
The useParams hook is used to access the path parameters from the URL.
For example, in the City component:
import { useParams } from 'react-router-dom';​

const City = () => {​
const { id } = useParams();​
return <div>City ID: {id}</div>;​
};​

export default City;
In this example, the useParams hook extracts the id parameter from the
URL, which can then be used within the component.
Using useSearchParams Hook
The useSearchParams hook is used to access and manipulate the search
parameters in the URL. For example:
import { useSearchParams } from 'react-router-dom';​

const City = () => {​
const [searchParams, setSearchParams] = useSearchParams();​
const lat = searchParams.get('lat');​
const lng = searchParams.get('lng');​

return (​
<div>​
<p>Latitude: {lat}</p>​
<p>Longitude: {lng}</p>​
</div>​
);​
};​

export default City;
useNavigate
The useNavigate hook in React Router v6 is a powerful utility that allows you
to programmatically navigate to different routes within your application.
This can be useful in various scenarios, such as redirecting users after a
form submission, handling navigation based on certain conditions, or
dynamically changing routes without using the <Link> component.
import React from 'react';​
import { useNavigate } from 'react-router-dom';​

const MyComponent = () => {​
const navigate = useNavigate();​

export default function handleButtonClick () {​
// Navigate to a new route​
navigate('/new-route');​
};​
return (​
<div>​
<button onClick={handleButtonClick}>Go to New Route</button>​
</div>​
);​
};
Options
The navigate function can take additional options for more control over the
navigation behavior.
1. Replace the current entry​
If you want to replace the current entry in the history stack (similar to how
window.location.replace works), you can use the replace option:
navigate('/new-route', { replace: true });
2. Navigate relative to the current location
You can also navigate relative to the current location:
// Go back one page​
navigate(-1);​
// Go forward one page​
navigate(1);​
// Go up one level in the URL hierarchy​
navigate('../');
Navigate component in React-Router
The Navigate element in React Router v6 is used to programmatically
redirect the user to a different route within your application. It is typically
used within the component's render logic to perform immediate redirects
based on certain conditions.
import { Navigate } from 'react-router-dom';​

export default function MyComponent () {​
const isLoggedIn = false; // Example condition​
if (!isLoggedIn) {​
return <Navigate to="/login" />;​
}​
return <div>Welcome to the protected page!</div>};
In this example, if the isLoggedIn condition is false, the component will
immediately redirect the user to the /login route.

Context in React
WHAT IS STATE MANAGEMENT?

TYPES OF STATE
STATE PLACEMENT OPTIONS

STATE MANAGEMENT TOOL OPTIONS


Performance Optimization and Advanced useEffect

To optimize performance in React applications, there are several tools and


techniques you can employ, as you've listed some already. Here's a
structured overview of each and how they contribute to performance
optimization:
1. Memoization (memo, useMemo, useCallback):
●​ memo: Higher-order component that memoizes a functional
component to prevent unnecessary re-renders.
●​ useMemo: Hook that memoizes the result of a function to cache
expensive computations between renders.
●​ useCallback: Hook that memoizes callbacks to prevent unnecessary
recreations of functions, particularly useful when passing callbacks to
child components.
2. Passing Elements as Children or Regular Props:
●​ Choosing between passing components as children
(<Component>{children}</Component>) or as regular props
(<Component prop={value} />) can affect performance based on how
often the component re-renders and how props are used.
3. useTransition:
●​ This is a React Concurrent Mode API that allows you to control the
rendering priority of certain components, improving perceived
performance by managing when updates are committed.
4. Using Fewer 3rd-Party Packages:
●​ Each additional package adds to the bundle size and potentially
increases the overhead of your application. Minimizing dependencies
can improve initial load times and runtime performance.
5. Code Splitting and Lazy Loading:
●​ Break your application into smaller chunks and load them
asynchronously (lazy loading) only when needed. This reduces the
initial bundle size and speeds up the initial render time.
Here's how you can implement these techniques:
●​ Memoization: Wrap components with React.memo, use useMemo to
memoize expensive computations, and useCallback to memoize
callbacks.
●​ Passing Elements: Choose between passing components as children or
props based on how often they change and whether they depend on
parent component state.
●​ useTransition: Use this API to improve perceived performance during
state changes by controlling when updates are visible to the user.
●​ Third-Party Packages: Be mindful of the impact of each package on
your application size and performance. Consider alternatives or
custom implementations where feasible.
●​ Code Splitting: Use dynamic imports (import() syntax) with React's
lazy loading (React.lazy) to split your application into smaller chunks
and load them only when necessary.

WHEN DOES A COMPONENTS INSTANCE RE-RENDER?


What is Memoization?

Memo Function

An Issue With Memo


useMemo and useCallback

memo vs useMemo vs useCallback

Feature React.memo useMemo useCallback

Purpose Optimize functional Memoize expensive Memoize functions


component calculations
re-renders
Type Higher-order Hook Hook
component
Usage Wrap functional Wrap a value/ Wrap a function
components computation
Paramet Component, optional Value/computatio Function, dependency
ers comparison function n, dependency array
array
Returns Memoized Memoized Memoized function
component value/computation
Re-eval On prop change (if On dependency On dependency
uation deep comparison change change
fails)
Commo Prevent re-rendering Expensive Event handlers that
n Use of a component with calculations that should not be
Case the same props should not re-run re-created on every
on every render render
Example React.memo(MyCom useMemo(() => useCallback(() =>
ponent, [compareFn]) computeExpensive handleEvent(), [deps])
Value(), [deps])
Typical When component When computation When passing
Usage renders frequently is expensive and functions to optimized
Context and props don't result is needed components or
change repeatedly dependencies of
other hooks

Bundle and Code Splitting

Normal Loading:
LazyLoading:

And add Routes between a Suspense Tag with fallback for loading spinner:

Do’s and Don’ts of Optimization

USEEFFECT RULES AND BEST PRACTICES


REMOVING UNNECESSARY DEPENDENCIES

WHEN NOT TO USE AN EFFECT


REDUX AND MODERN REDUX TOOLKIT (WITH THUNKS)

Do You Need To Learn Redux?


THE MECHANISM OF THE USEREDUCER HOOK V/S REDUX
REDUX MIDDLEWARE AND THUNKS
REDUX TOOLKIT - RTK

Context API vs REDUX

You might also like