React Syllabus
React Syllabus
9. State Management (Redux & Context) Higher-Order Components (HOCs): Reuse component logic (e.g.,
authentication checks).
Redux: Predictable state container with store, actions, and reducers. Render Props: Pass functions to dynamically control component rendering.
o Redux Toolkit: Simplifies Redux with slices and reducers. Compound Components: Components that work together to control state.
React Context as State Management: Use useReducer with Context for Custom Hooks: Encapsulate complex logic, reusability (e.g., useFetch,
lighter applications. useAuth).
Example: Manage a shopping cart with Redux, including actions like Example: Create an authentication HOC to control protected routes.
addToCart and removeFromCart.
13. Testing in React
10. React Query and Data Fetching
Unit Testing:
React Query: Handles data fetching, caching, synchronization. o Use Jest and React Testing Library for isolated testing.
o Hooks: useQuery, useMutation. o Test component rendering, state, props, and events.
o Automates caching and background refreshing of data. Integration and E2E Testing:
Example: Fetch and cache API data for products in an e-commerce app. o Cypress for end-to-end testing.
o Test flows like login, adding items to a cart.
11. Optimizing React Performance Example: Test if a Login button renders correctly based on authentication
state.
Code Splitting: Load only necessary parts of the app using dynamic imports
and React’s lazy and Suspense. 14. Server-Side Rendering (SSR) and Next.js
Memoization:
o React.memo: Wraps components to prevent unnecessary re- SSR with Next.js:
renders. o Server-rendered components for faster load and improved SEO.
o useCallback and useMemo: Memoize functions and values to avoid o getServerSideProps for data-fetching on each request.
unnecessary recalculations. Static Site Generation (SSG):
Avoiding Large Re-renders: o Pre-render pages at build time for performance.
o getStaticProps, getStaticPaths.
Example: Pre-render product pages in an e-commerce site for SEO and faster o Webpack plugins for code splitting, minification, and tree shaking.
load times. Deployment:
o Platforms: Vercel, Netlify, AWS Amplify.
15. Progressive Web Apps (PWA) Example: Configure a custom Webpack config for tree shaking and deploy to
Netlify.
Service Workers:
o Cache assets for offline use. ______________________________________________________________________
o Add with create-react-app or manually with Workbox. Perfromance Optimization:
Manifest Files: Defines app icons, theme color, and splash screen.
Example: Convert a React weather app into a PWA with offline capabilities. Optimizing performance in a React application involves reducing unnecessary re-
renders, minimizing the amount of data processed, and improving loading and data
16. React and GraphQL management strategies. Here are several techniques:
Caching and Re-fetching Strategies: Use caching strategies for frequent data, In React projects, handling APIs effectively requires managing HTTP requests, data,
such as React Query or SWR for data fetching. and caching to ensure efficient and reliable data fetching. Here are several methods
Batch Requests: Combine API requests to reduce the number of calls. and patterns commonly used for handling APIs in React applications:
1. Using the Fetch API timeout: 1000,
headers: { "X-Custom-Header": "foobar" }
Basic Fetch: The built-in fetch API allows you to make HTTP requests easily. });
It’s a straightforward approach for simple data fetching needs.
Async-Await Pattern: Using async and await with fetch to handle promises async function fetchData() {
provides a cleaner syntax for managing asynchronous operations. try {
Error Handling: Add error handling (e.g., try-catch blocks) around fetch const response = await api.get("/data");
requests, especially for managing network or server errors. return response.data;
} catch (error) {
async function fetchData() { console.error("Axios error: ", error);
try { }
const response = await fetch("https://api.example.com/data"); }
if (!response.ok) throw new Error("Network response was not ok");
const data = await response.json(); 3. React Query (TanStack Query)
return data;
} catch (error) { Data Fetching and Caching: React Query is a powerful library for handling
console.error("Fetch error: ", error); data fetching, caching, and synchronization in React applications.
} Automatic Refetching and Background Updates: Automatically re-fetches
} data in the background when the query becomes stale or upon re-mounting
the component.
2. Axios Optimistic Updates: Allows for immediate UI updates (optimistic updates)
while awaiting confirmation from the API.
Axios Library: Axios is a popular promise-based HTTP client that simplifies API
requests, offering automatic JSON parsing, better error handling, and HTTP import { useQuery } from "react-query";
request interceptors.
Request and Response Interceptors: Use Axios interceptors to manage function useData() {
things like attaching auth tokens, handling errors globally, or logging return useQuery("data", () =>
requests. fetch("https://api.example.com/data").then(res => res.json())
Instance-Based Configurations: You can create reusable Axios instances with );
preset configurations for specific API endpoints. }
return ( Concurrent Mode: React Suspense, combined with Concurrent Mode, helps
<DataContext.Provider value={data}> manage async operations in a way that provides better loading states and
{children} fallback mechanisms.
</DataContext.Provider> Data Fetching Libraries: Although still experimental, some libraries support
); Suspense-based data fetching, providing native React patterns for async data.
};
Summary Table
export const useData = () => useContext(DataContext);
Method Key Features Best For
7. Redux with Redux-Thunk or Redux-Saga Fetch API Native, simple syntax Basic data fetching needs
Apps needing more control and
Redux-Thunk: Allows dispatching asynchronous actions within Redux. Useful Axios Extended API, interceptors
config
for simpler async workflows like handling API requests. Caching, refetching, optimistic
Redux-Saga: Middleware for managing complex asynchronous tasks, React Query Data-heavy applications
updates
especially when dealing with multiple API requests, retries, and background
Lightweight, real-time data
tasks. SWR Cache-first, real-time revalidation
fetching
Apollo Client GraphQL-based, subscriptions GraphQL APIs and real-time data
// Redux with Redux-Thunk Example
import { createStore, applyMiddleware } from "redux"; Apps with shared data
Context API Global state and API management
import thunk from "redux-thunk"; requirements
Redux
Async actions in Redux Simple async Redux workflows
const fetchData = () => async dispatch => { Thunk
try { Complex async workflows with
Redux Saga Complex state management
const response = await fetch("https://api.example.com/data"); Redux
const data = await response.json(); Suspense Experimental, concurrent mode Emerging async data patterns
dispatch({ type: "SET_DATA", payload: data });
Each method provides unique benefits and is suitable for different project
requirements. Choosing the right one depends on the complexity, data requirements,
and architectural needs of your application. Context API
What It Is: A built-in React feature for managing state and sharing data
between components.
API TYPES: Purpose: Helps avoid "prop drilling" (passing props through many layers of
API Type Best For Key Features components).
CRUD operations, Stateless, JSON or XML, HTTP Use Case: Ideal for sharing data like user info, themes, or settings across
REST different parts of a React app.
standardized interfaces methods
High-security, compliant Protocol-based, XML format, Scope: Works only within your React application.
SOAP
environments strict standards
RESTful API
Flexible, nested data Query language, single endpoint,
GraphQL
structures fetch specific fields
What It Is: A way for web applications to communicate over the internet
High-performance HTTP/2, Protocol Buffers,
gRPC using standard HTTP methods (GET, POST, PUT, DELETE).
microservices supports streaming
Purpose: Allows different systems (like a client and a server) to exchange
Real-time, low-latency Full-duplex, persistent data.
WebSocket
communication connection Use Case: Best for fetching or sending data to a server (e.g., getting user data
JSON-RPC & XML- Minimal setup, uses JSON or from a database).
Lightweight remote calls
RPC XML Scope: Works across different applications, not just React.
API documentation and Defines RESTful APIs in machine-
OpenAPI
design readable format Summary
Continuous real-time data Pushes data to clients, supports
Streaming API Use Context API for sharing state within a React app.
updates real-time analytics
Data with complex Exposes data as nodes with Use RESTful API for interacting with a server to fetch or update data.
Graph API
relationships relationships
Specific language or Tied to specific libraries or
Library/Framework
framework usage languages
In-house system Restricted access, internal
Internal/Private
communication purposes
B2B data sharing with Requires authentication and
Partner
restricted access usually contractual
Bundling multiple calls into Efficient, reduces number of
Composite
one client requests