Skip to content

Commit

Permalink
fix format frontend/react/*
Browse files Browse the repository at this point in the history
  • Loading branch information
zlatanpham committed Oct 29, 2024
1 parent bb74e8d commit 8ea6fb0
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 88 deletions.
16 changes: 8 additions & 8 deletions Frontend/react/code-splitting.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ function App() {
}
```

**Explanation:**
Explanation:

- `React.lazy` dynamically imports each component.
- `Suspense` shows a fallback (loading spinner) while the component loads.
Expand Down Expand Up @@ -102,7 +102,7 @@ function App() {
}
```

**Explanation:**
Explanation:

- The `UserProfile` component only loads when showProfile is true.
- `Suspense` ensures that a fallback UI (loading spinner) is displayed while `UserProfile` is being loaded.
Expand Down Expand Up @@ -133,7 +133,7 @@ function DateFormatter({ date }) {
}
```

**Explanation:**
Explanation:

- The date-fns library only loads when DateFormatter is rendered.
- This avoids including the entire library in the initial bundle, saving on bundle size.
Expand Down Expand Up @@ -167,7 +167,7 @@ function App() {
}
```

**Explanation:**
Explanation:

- `react-loadable` provides a loading component that displays based on certain conditions, such as past delay time or error occurrence.
- This allows you to handle cases where loading might take a long time or fail altogether, providing a better user experience.
Expand Down Expand Up @@ -219,9 +219,9 @@ module.exports = {
}
```

**Explanation**:
Explanation:

- SplitChunksPlugin creates a vendors chunk with common dependencies, reducing redundancy and improving caching.
- `SplitChunksPlugin` creates a vendors chunk with common dependencies, reducing redundancy and improving caching.

**Use Case:**

Expand All @@ -239,9 +239,9 @@ function ImageComponent() {
}
```

**Explanation:**
Explanation:

- The loading="lazy" attribute ensures the image loads only when it’s about to enter the viewport.
- The `loading="lazy"` attribute ensures the image loads only when it’s about to enter the viewport.

**Benefits:**

Expand Down
2 changes: 1 addition & 1 deletion Frontend/react/component-composition-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function DataFetcher({ render }) {
}

// Usage:
;<DataFetcher render={(data) => <DisplayData data={data} />} />
<DataFetcher render={(data) => <DisplayData data={data} />} />
```

**When to Use Render Props**:
Expand Down
23 changes: 12 additions & 11 deletions Frontend/react/design-system-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,19 +139,22 @@ This approach allows the Button component to be reusable, enabling different col

### 4. Establish and Use a Component Library Framework (Storybook)

**Storybook** is a popular tool for creating isolated component libraries, documenting components, and allowing team members to interact with components outside of the application environment.
[Storybook](https://storybook.js.org/) is a popular tool for creating isolated component libraries, documenting components, and allowing team members to interact with components outside of the application environment.

1. **Set up Storybook**: Install Storybook in your React project.
**Set up Storybook**

Install Storybook in your React project.

```sh
npx sb init
```

2. **Write Stories for Components**: Each component should have its own story, describing its appearance with various props and states.
**Write Stories for Components**

**Example: Button.stories.js**
Each component should have its own story, describing its appearance with various props and states.

```jsx
// Example: Button.stories.js
import React from 'react'
import { Button } from './Button'

Expand All @@ -178,9 +181,8 @@ Design systems must prioritize accessibility to create inclusive applications. F

- **Aria Roles and Attributes**: Use ARIA attributes for interactive components like buttons, modals, and dialogs to improve screen reader support.

**Example: Accessible Button with ARIA**

```jsx
// Example: Accessible Button with ARIA
const Button = ({ label, onClick, ariaLabel, variant = 'primary' }) => (
<button onClick={onClick} style={{ backgroundColor: tokens.colors[variant] }} aria-label={ariaLabel}>
{label}
Expand All @@ -190,9 +192,8 @@ const Button = ({ label, onClick, ariaLabel, variant = 'primary' }) => (

- **Keyboard Navigation**: Ensure that all components can be navigated via keyboard. Focus management is crucial, especially for modal dialogs or dynamic components like carousels.

**Example: Focus Management in a Modal**

```jsx
// Example: Focus Management in a Modal
import { useEffect, useRef } from 'react'

const Modal = ({ isOpen, onClose, children }) => {
Expand Down Expand Up @@ -226,7 +227,7 @@ To support **themes** (e.g., dark and light modes), use **context providers** to

**Example: Theming with Context**

**1. Create Theme Context:**
1. Create Theme Context:

```jsx
import React, { createContext, useContext, useState } from 'react'
Expand All @@ -247,7 +248,7 @@ export const ThemeProvider = ({ children }) => {
export const useTheme = () => useContext(ThemeContext)
```

**2. Consume Theme Context in Components:**
2. Consume Theme Context in Components:

```jsx
const ThemedButton = ({ label }) => {
Expand All @@ -265,7 +266,7 @@ const ThemedButton = ({ label }) => {
}
```

**3. Switch Themes in App:**
3. Switch Themes in App:

```jsx
function App() {
Expand Down
40 changes: 17 additions & 23 deletions Frontend/react/hook-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,12 @@ Hooks architecture in React refers to the systematic approach of using hooks to

### Key Concepts in Hooks Architecture

1. **Separation of Concerns with Custom Hooks**
2. **Encapsulating Side Effects**
3. **Dependency Management in Hooks**
4. **Combining Multiple Custom Hooks**
5. **Best Practices for Custom Hooks**
- Separation of Concerns with Custom Hooks
- Encapsulating Side Effects
- Dependency Management in Hooks
- Combining Multiple Custom Hooks

---

### 1. Separation of Concerns with Custom Hooks
### Separation of Concerns with Custom Hooks

By creating custom hooks, we can isolate specific pieces of logic or state, making components simpler and easier to test. Custom hooks follow the same naming conventions and usage patterns as built-in hooks but encapsulate domain-specific or app-specific logic.

Expand All @@ -49,7 +46,7 @@ function useFetch(url) {
}
```

**Usage**:
Usage:

```js
function UserProfile({ userId }) {
Expand All @@ -67,7 +64,7 @@ function UserProfile({ userId }) {
- **Reusability**: The `useFetch` hook can be used in any component needing data from an API.
- **Isolation of Concerns**: Data fetching logic is isolated, keeping components focused on UI and presentation.

### 2. Encapsulating Side Effects
### Encapsulating Side Effects

Side effects (like fetching data, managing subscriptions, or setting timeouts) often clutter component code. By moving these side effects into custom hooks, we can encapsulate the logic and improve component readability.

Expand All @@ -83,7 +80,7 @@ function useDocumentTitle(title) {
}
```

**Usage**:
Usage:

```js
function HomePage() {
Expand All @@ -97,7 +94,7 @@ function HomePage() {
- **Isolation of Side Effects**: The document title logic is separate from the component's main UI, simplifying the component.
- **Reusability**: `useDocumentTitle` can be reused across pages or components that need to set the document title.

### 3. Dependency Management in Hooks
### Dependency Management in Hooks

Custom hooks require careful handling of dependencies to avoid bugs, stale data, or unintended behaviors. `useEffect`, `useMemo`, and `useCallback` hooks depend on stable dependencies to function predictably.

Expand All @@ -118,7 +115,7 @@ function useExpensiveCalculation(data) {
}
```

**Usage**:
Usage:

```js
function Stats({ numbers }) {
Expand All @@ -134,7 +131,7 @@ function Stats({ numbers }) {

> In the future, this step will be handled automatically by [React Compiler](https://react.dev/learn/react-compiler#what-does-the-compiler-do)
### 4. Combining Multiple Custom Hooks
### Combining Multiple Custom Hooks

For more complex scenarios, multiple custom hooks can be combined, keeping components modular and avoiding deeply nested hooks. You can chain hooks to build up increasingly complex functionality without cluttering a single hook.

Expand Down Expand Up @@ -185,11 +182,11 @@ function Dashboard({ userId }) {
- **Modularity**: Each hook handles a specific concern (auth or fetching data), so they're independently reusable and testable.
- **Encapsulation**: The component doesn't need to understand the logic inside each hook, only the returned data and functions.

### 5. Best Practices for Custom Hooks
### Best Practices for Custom Hooks

1. **Use Clear Naming Conventions**: Name hooks descriptively, starting with `use`, such as `useAuth`, `useFetchData`, or `useToggle`. This helps with readability and code consistency.
**Use Clear Naming Conventions**: Name hooks descriptively, starting with `use`, such as `useAuth`, `useFetchData`, or `useToggle`. This helps with readability and code consistency.

2. **Return Only Necessary Data and Functions**: Custom hooks should return only the data and functions the component actually needs. This minimizes the hook's API surface and reduces complexity.
**Return Only Necessary Data and Functions**: Custom hooks should return only the data and functions the component actually needs. This minimizes the hook's API surface and reduces complexity.

```js
// Better: return only what's needed
Expand All @@ -200,7 +197,7 @@ function useToggle(initialState = false) {
}
```

1. **Handle Edge Cases and Errors Gracefully**: Build error handling directly into hooks, where applicable. This keeps components from dealing with low-level error handling, focusing only on displaying relevant information to the user.
**Handle Edge Cases and Errors Gracefully**: Build error handling directly into hooks, where applicable. This keeps components from dealing with low-level error handling, focusing only on displaying relevant information to the user.

```js
function useFetch(url) {
Expand All @@ -218,9 +215,7 @@ function useFetch(url) {
}
```

1. **Encapsulate Complex State Logic**: If you find yourself managing complex state logic (e.g., multiple variables, resetting state), consider using `useReducer` within the hook.

**Example: Managing Form State with `useReducer`**
**Encapsulate Complex State Logic**: If you find yourself managing complex state logic (e.g., multiple variables, resetting state), consider using `useReducer` within the hook.

```jsx
import { useReducer } from 'react'
Expand All @@ -246,7 +241,7 @@ function useForm(initialState) {
}
```

1. **Testing Custom Hooks**: Test custom hooks in isolation to ensure they behave as expected under various scenarios. Tools like **React Testing Library's `renderHook`** make it easy to test hooks directly.
**Testing Custom Hooks**: Test custom hooks in isolation to ensure they behave as expected under various scenarios. Tools like **React Testing Library's `renderHook`** make it easy to test hooks directly.

```js
import { renderHook, act } from '@testing-library/react-hooks'
Expand Down Expand Up @@ -285,7 +280,6 @@ function useAuth() {
}

// useUserData.js

import useFetch from './useFetch'

function useUserData(userId) {
Expand Down
34 changes: 18 additions & 16 deletions Frontend/react/rendering-strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,27 @@ Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static-Site Genera

### 1. Client-Side Rendering (CSR)

**CSR** is the default rendering approach in React applications, where everything from data fetching to rendering happens in the browser. The server delivers a minimal HTML file with a JavaScript bundle, and React takes over from there, rendering the content on the client's side.
CSR is the default rendering approach in React applications, where everything from data fetching to rendering happens in the browser. The server delivers a minimal HTML file with a JavaScript bundle, and React takes over from there, rendering the content on the client's side.

#### How It Works:
#### How It Works

- The browser downloads the JavaScript bundle, which contains the React code.
- React builds the UI on the client by executing the JavaScript code.
- Data fetching happens after the page loads, potentially leading to a delay before content appears.

#### Advantages of CSR:
#### Advantages of CSR

- **Fast Initial Deployment**: Easier to deploy and manage since there's no server-rendering setup.
- **Rich Interactivity**: Great for SPAs (Single Page Applications) with dynamic, highly interactive UI elements.
- **Simplified Development**: Client-side data fetching and rendering simplify development in many scenarios.

#### Disadvantages of CSR:
#### Disadvantages of CSR

- **Initial Load Time**: Users may experience a blank page or loading spinner until the JavaScript bundle downloads and renders.
- **SEO Challenges**: Since the HTML is minimal, search engines may struggle to crawl and index content, although some modern crawlers can render JavaScript.
- **Performance**: Large bundles can lead to slow page load times, especially on low-bandwidth connections.

#### Example in React:
#### Example in React

In CSR, data fetching happens on the client side, typically using hooks like `useEffect`.

Expand All @@ -55,27 +55,27 @@ function UserProfile({ userId }) {

### 2. Server-Side Rendering (SSR)

**SSR** generates HTML on the server for each request. When the user requests a page, the server processes the JavaScript, fetches any necessary data, and returns a fully-rendered HTML page. React components are rendered to HTML strings on the server and sent to the client, where React "hydrates" (attaches event listeners) to the HTML.
SSR generates HTML on the server for each request. When the user requests a page, the server processes the JavaScript, fetches any necessary data, and returns a fully-rendered HTML page. React components are rendered to HTML strings on the server and sent to the client, where React "hydrates" (attaches event listeners) to the HTML.

#### How It Works:
#### How It Works

- The server generates HTML with the initial content and sends it to the client.
- The client receives a fully-rendered HTML page and hydrates it, enabling interactivity.
- Additional JavaScript for further user interactions loads in the background.

#### Advantages of SSR:
#### Advantages of SSR

- **Improved SEO**: The initial HTML page is fully rendered, making it easily crawlable by search engines.
- **Faster Time to Interactive (TTI)**: The user sees the fully-rendered content sooner, as it doesn't rely solely on client-side JavaScript for initial render.
- **Content Accessibility**: Even users on slow networks or with JavaScript disabled can see the initial page content.

#### Disadvantages of SSR:
#### Disadvantages of SSR

- **Server Load**: Each request requires the server to render the page, increasing server workload, especially with many requests.
- **Complexity**: Requires server infrastructure and additional setup, which can increase complexity.
- **Hydration Time**: The browser still needs to download JavaScript and hydrate the page, which can create a slight delay for interactivity.

#### Example in Next.js:
#### Example in Next.js

Next.js is a React framework that simplifies SSR. With Next.js, you can use `getServerSideProps` to fetch data and render it on the server.

Expand All @@ -99,27 +99,27 @@ export default function UserProfile({ user }) {

### 3. Static-Site Generation (SSG)

**SSG** generates HTML at build time. Unlike SSR, which renders HTML on each request, SSG pre-renders pages as static files and serves them on request. This is ideal for content that doesn't change frequently, as it combines the benefits of SSR with the speed of serving static files.
SSG generates HTML at build time. Unlike SSR, which renders HTML on each request, SSG pre-renders pages as static files and serves them on request. This is ideal for content that doesn't change frequently, as it combines the benefits of SSR with the speed of serving static files.

#### How It Works:
#### How It Works

- The pages are pre-rendered at build time, creating static HTML files.
- When a user requests a page, the server serves the static HTML directly from a CDN or hosting server.
- Any dynamic content or interactivity can be added client-side, often using JavaScript to fetch data or modify the UI after load.

#### Advantages of SSG:
#### Advantages of SSG

- **Fast Performance**: Since the pages are static files, they load very quickly from a CDN or server.
- **SEO-Friendly**: Like SSR, the static HTML is crawlable by search engines.
- **Low Server Load**: No need to generate HTML per request, reducing server resources.

#### Disadvantages of SSG:
#### Disadvantages of SSG

- **Less Flexibility**: Pages are generated at build time, so content updates require a new build and deployment.
- **Not Ideal for Highly Dynamic Content**: SSG is less suitable for frequently changing content, as updates won't appear until the next build.
- **Extra Build Time**: Large sites can have long build times if each page needs to be generated statically.

#### Example in Next.js:
#### Example in Next.js

In Next.js, `getStaticProps` generates static pages at build time. This is perfect for content like blog posts or product pages.

Expand Down Expand Up @@ -176,7 +176,9 @@ In some cases, applications use a **hybrid approach** to leverage the strengths
- **Next.js** allows you to use SSG for pages with static content, SSR for dynamic pages, and CSR for client-specific interactions.
- **Incremental Static Regeneration (ISR)** in Next.js enables automatic regeneration of static pages at a specified interval, combining the benefits of SSG and SSR for frequently updated content.

**Example Hybrid Approach in Next.js**: In this example, we use SSG with ISR for product pages and CSR for interactive features like adding items to a cart.
**Example Hybrid Approach in Next.js**

In this example, we use SSG with ISR for product pages and CSR for interactive features like adding items to a cart.

```jsx
// pages/product/[id].js
Expand Down
4 changes: 2 additions & 2 deletions Frontend/react/state-management-strategy.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ function UserProfile({ userId }) {
}

// Usage in App:
;<QueryClientProvider client={queryClient}>
<QueryClientProvider client={queryClient}>
<UserProfile userId={1} />
</QueryClientProvider>
```
Expand Down Expand Up @@ -212,7 +212,7 @@ function UserComponent() {
}

// Usage:
;<AppProvider>
<AppProvider>
<UserComponent />
</AppProvider>
```
Expand Down
Loading

0 comments on commit 8ea6fb0

Please sign in to comment.