Advanced React
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?
useState vs useReducer
When to Use the useReducer hook?
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
Memo Function
Normal Loading:
LazyLoading:
And add Routes between a Suspense Tag with fallback for loading spinner: