0% found this document useful (0 votes)
47 views

React Syllabus

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

React Syllabus

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

1. React Basics o useReducer: Manages complex state logic.

o useCallback, useMemo: Optimize performance by memoizing


 JSX (JavaScript XML): Syntax that combines HTML and JavaScript. functions and values.
o Example: <h1>Hello, {name}</h1> renders name as a variable.  Example: A ToDoList with state for tasks and effects for fetching tasks from
 Components: Reusable building blocks; can be functional or class-based. an API.
o Functional Components: Defined with functions, use hooks for state
and side effects. 5. Event Handling and Conditional Rendering
o Class Components: Defined with ES6 classes, use this.state and
lifecycle methods.  Event Handling: Add event listeners using camelCase syntax (onClick,
o Example: A UserProfile component that displays user data. onChange).
 Conditional Rendering: Use if, ternary operators, or && to render elements
2. State and Props conditionally.
 Example: Show a "logged in" message if a user is authenticated.
 Props: Data passed from parent to child components; read-only.
 State: Data managed within a component; use useState hook or this.setState 6. Forms and Controlled Components
in class components.
 Props vs State:  Controlled Components: Inputs controlled by React state.
o Props are external, whereas state is internal to the component.  Uncontrolled Components: Inputs managed by the DOM itself.
 Example: A counter component with a button to increment its count.  Form Submission and Validation:
o Use onSubmit event handler.
3. React Lifecycle Methods (Class Components) o Validate inputs with custom logic or libraries like Yup or Formik.
 Example: A login form with email and password fields.
 Mounting: constructor, componentDidMount.
 Updating: componentDidUpdate. 7. Context API
 Unmounting: componentWillUnmount.
 Example: Using componentDidMount to fetch data after a component  Context API: Passes data through the component tree without prop-drilling.
mounts.  Creating and Using Context:
o Create with React.createContext().
4. React Hooks (Functional Components) o Provide with <Context.Provider> and consume with useContext or
<Context.Consumer>.
 Basic Hooks:  Example: Manage theme or authentication state with context.
o useState: Manages state.
o useEffect: Runs side effects (e.g., fetch data). 8. React Router (v5 and v6)
 Advanced Hooks:
o useContext: Consumes context values.  Core Components:
o BrowserRouter, Route, Link, Switch (v5), Routes (v6). o Optimize state placement, split large components, and use React
 Dynamic Routing: Profiler.
o Pass parameters in URLs (e.g., /users/:id).  Virtualization: Display only visible list items with libraries like react-window
o Use useParams to retrieve parameters in v6. or react-virtualized.
 Protected Routes:  Example: Improve list rendering performance with react-window.
o Guard routes based on authentication state.
 Example: Navigation in a blog app where each post is loaded based on its ID. 12. Advanced Component Patterns

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:

 Apollo Client: 1. Avoid Unnecessary Re-renders


o Manage GraphQL queries and mutations with useQuery and
useMutation.  React.memo: Wrap components with React.memo to prevent them from re-
 Optimized Data Fetching: rendering unless their props change.
o Use fragments and caching.  useMemo and useCallback Hooks:
 Example: Use Apollo Client to fetch user data and cache responses. o useMemo: Memoize expensive calculations and only recompute
them when dependencies change.
17. Error Handling and Error Boundaries o useCallback: Memoize functions to prevent re-creation on every
render.
 Error Boundaries:  Key Prop Optimization in Lists: Ensure that list items have a stable, unique
o Catch JavaScript errors in components with componentDidCatch. key prop to avoid unnecessary re-renders.
o Useful for logging and showing fallback UIs.
 Global Error Handling: Handle errors across multiple components using 2. Efficient State Management
context.
 Example: Show a fallback UI for an image gallery if an error occurs.  Minimize Stateful Components: Move state up to the highest necessary level
in the component tree and pass props down to stateless children.
18. Build Configuration and Deployment  Split State: For complex applications, splitting the state into smaller, focused
pieces can reduce re-renders. This can be achieved using Context API, Redux,
 Environment Configuration: or Zustand.
o Use .env files for environment-specific variables (e.g., API  Debouncing and Throttling: In functions handling rapid state changes (e.g., in
endpoints). user input or scroll events), use debouncing or throttling to control
 Optimizing Bundles: frequency.
3. Optimize Rendering with Virtualization  Pagination and Infinite Scrolling: Use pagination or infinite scrolling in lists to
limit the amount of data rendered at once.
 React-Window or React-Virtualized: For long lists or tables, use these
libraries to render only visible elements and avoid rendering the entire list, 8. Service Workers and Caching Strategies
which significantly improves performance in DOM-intensive views.
 Service Workers: Use service workers for caching static assets and API
4. Lazy Loading and Code Splitting responses to enable offline functionality and faster load times.
 Caching: Cache frequently requested data and assets using browser storage
 React.lazy and Suspense: Code-split components by loading them only when or libraries like localStorage, sessionStorage, or indexedDB where
needed using React.lazy and Suspense. This helps reduce the initial bundle appropriate.
size and improves page load time.
 Dynamic Imports: Load modules dynamically as needed, which can be 9. Optimize CSS and Reduce Render Blocking
helpful for larger libraries or third-party code.
 CSS Minification: Minify CSS to reduce load time.
5. Optimizing Image Loading and Asset Management  CSS in Critical Path: Use @font-face, critical CSS, and inline CSS for above-
the-fold content to improve page load time.
 Responsive and Lazy Loading Images: Use responsive images with srcset and  Avoid CSS Preprocessors in Production: Minimize complex CSS pre-
lazy load images only when they're visible. processing and only use production-optimized CSS.
 Image Compression: Compress and optimize image sizes to reduce download
times. 10. Use Browser DevTools to Analyze Performance
 Use WebP Format: The WebP image format often provides better
compression than traditional formats (JPEG, PNG).  React DevTools Profiler: Use the Profiler to analyze rendering patterns and
identify bottlenecks.
6. Reduce Rendered Content Size  Browser DevTools: Use the Performance tab to monitor layout shifts, paint
events, and the time taken to execute scripts.
 Avoid Large Inline Styles and JavaScript: Keep the inline styles and script
blocks minimal, and leverage CSS-in-JS libraries like styled-components or Each of these techniques, when thoughtfully applied, can help improve the
Emotion for smaller component styles. performance and responsiveness of a React application, particularly as it scales.
 Tree Shaking: Ensure unused code is removed with tree shaking, and avoid
loading unnecessary code dependencies.

7. Optimize API Calls and Data Fetching

 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. }

import axios from "axios"; function Component() {


const { data, error, isLoading } = useData();
const api = axios.create({
baseURL: "https://api.example.com", if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error loading data</p>;  Real-Time Data with Subscriptions: Apollo Client supports GraphQL
subscriptions for handling real-time updates.
return <div>{JSON.stringify(data)}</div>;
} import { useQuery, gql } from "@apollo/client";

4. SWR (Stale-While-Revalidate) const GET_DATA = gql`


query GetData {
 Simple Data Fetching: SWR (from Vercel) is a lightweight library focusing on data {
revalidation, caching, and fallback data for fast and reliable data fetching. id
 Real-Time Data Syncing: SWR refetches data in the background on focus or name
interval, keeping data fresh. }
 Error Handling and Loading State: SWR automatically manages the loading }
and error states, making it simple to use. `;

import useSWR from "swr"; function Component() {


const { loading, error, data } = useQuery(GET_DATA);
const fetcher = url => fetch(url).then(res => res.json());
if (loading) return <p>Loading...</p>;
function Component() { if (error) return <p>Error loading data</p>;
const { data, error } = useSWR("https://api.example.com/data",
fetcher); return <div>{data.data.map(item => <p
key={item.id}>{item.name}</p>)}</div>;
if (error) return <p>Error loading data</p>; }
if (!data) return <p>Loading...</p>;
6. Context API with Custom Hooks
return <div>{JSON.stringify(data)}</div>;
}  Centralized Data Handling: Create a context provider with custom hooks for
accessing API data globally across the app.
5. GraphQL  Local State Management: Manage complex state derived from API responses
using React's Context API for data shared between components.
 Apollo Client: Apollo Client is a popular library for managing GraphQL
requests in React, supporting data fetching, caching, and state management. import React, { createContext, useContext, useState, useEffect } from "react";
 Declarative Data Fetching: Write complex data queries and mutations in a
single request, reducing the number of API calls needed. const DataContext = createContext();
export const DataProvider = ({ children }) => { } catch (error) {
const [data, setData] = useState(null); console.error("Error:", error);
}
useEffect(() => { };
fetch("https://api.example.com/data")
.then(response => response.json()) const store = createStore(reducer, applyMiddleware(thunk));
.then(data => setData(data));
}, []); 8. React Suspense (Experimental)

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

You might also like