跳到主要内容

11 篇博文 含有标签「reactjs」

查看所有标签

React Best Practices Guide - 2025

· 阅读需 11 分钟

Below is a clean, concise React Best Practices document that covers: ✔ Avoiding unnecessary re-renders ✔ Comparing Redux vs React built-in state vs Zustand ✔ When to use useMemo and useCallback ✔ Real-world examples and patterns


React Best Practices Guide (Rendering, State Management, and Memoization)

1. Avoiding Unnecessary Re-renders​

Unnecessary re-renders slow down your UI and degrade performance. The core rules to prevent them:

1.1 Keep State Local and Minimal​

  • Only store what the component needs to render.
  • Don’t store derived data in state (compute when needed).
  • Lift state only when necessary.

✔ Good:

const [count, setCount] = useState(0);

✘ Bad:

const [double, setDouble] = useState(count * 2); // derived → no need

1.2 Break Components into Smaller Memoized Pieces​

  • Smaller components re-render less often.
  • Apply React.memo() to memoize pure components.
const UserRow = React.memo(({ user }) => {
return <div>{user.name}</div>;
});

1.3 Avoid Recreating Objects/Arrays in Props​

Passing a new object reference triggers re-renders.

✘ Bad:

<UserList filters={{ active: true }} /> // new object every time

✔ Good:

const filters = useMemo(() => ({ active: true }), []);
<UserList filters={filters} />

1.4 Avoid Inline Functions When Passing to Children​

Inline functions cause new references → re-render.

✔ Solve with useCallback (see section 4)



2. State Management Comparison

2.1 React Built-in State (useState, useReducer, context)​

✔ Best for:​

  • Local UI state
  • Small/medium apps
  • Component-specific logic

✔ Pros:​

  • Simple
  • No external dependency
  • Fast, minimal overhead

✘ Cons:​

  • Context re-renders entire subtree
  • Harder for large global state
  • Not ideal for complex async logic

2.2 Redux Toolkit (RTK)​

✔ Best for:​

  • Large applications
  • Complex global state workflows
  • Predictable state transitions
  • Time travel debugging
  • Strict immutability, stable dev tooling

✔ Pros:​

  • Centralized, predictable state
  • Excellent debugging/devtools
  • Built-in async support (RTK Query)

✘ Cons:​

  • More boilerplate than alternatives (though RTK solved most)
  • Heavy for small apps
  • Requires good understanding of reducers, actions

2.3 Zustand​

A lightweight state manager that avoids context re-rendering.

✔ Best for:​

  • Medium/large apps needing global state
  • Performance-sensitive apps
  • Real-time or frequently updated data (e.g., WebGL apps, dashboards)

✔ Pros:​

  • Extremely simple API (useStore)
  • No provider required
  • Selectors prevent unnecessary re-renders
  • Small footprint
const useStore = create((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
}));

✔ Component re-renders only when the selected part changes:

const count = useStore((s) => s.count); // selector = optimized re-render

✘ Cons:​

  • No built-in time travel/debugging like Redux
  • Fewer guardrails for large teams

Summary Table​

FeatureReact Built-inRedux ToolkitZustand
App sizeSmall–MediumMedium–LargeSmall–Large
Global stateLimited (Context)ExcellentExcellent
PerformanceGoodGoodBest
BoilerplateLowMediumVery Low
DevtoolsBasicExcellentGood
Re-render controlWeakMediumStrong


3. useMemo and useCallback — When and Why

3.1 useMemo​

Memoizes a computed value.

✔ Use when:​

  • Expensive calculations
  • Stable object/array references needed
  • Props require referential equality to avoid re-render

Example:

const sortedUsers = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
);

3.2 useCallback​

Memoizes a function reference.

✔ Use when:​

  • Passing callbacks to memoized children
  • Functions used in dependencies that should not change
  • Avoiding new function reference on each render

Example:

const handleClick = useCallback(() => {
doSomething(value);
}, [value]);

3.3 Real-World Example Combining Both​

const filters = useMemo(() => ({ active: true }), []);

const onSelect = useCallback((id) => {
setSelected(id);
}, []);

When NOT to use them​

Overuse causes more harm than good.

❌ Don’t use them on trivial values/functions. ❌ Only optimize where profiling shows need.



4. Real-World Scenarios and Patterns

4.1 Optimizing a Large Table​

Use memoized rows + stable props

const Row = React.memo(({ item, onSelect }) => { … });

const onSelect = useCallback((id) => { … }, []);

4.2 Using Zustand for Real-Time WebSocket Updates​

const useStore = create((set) => ({
messages: [],
addMessage: (m) => set((s) => ({ messages: [...s.messages, m] })),
}));

React components subscribe to slices:

const messages = useStore((s) => s.messages);

Only re-renders on message changes—ideal for chat/dashboards.


4.3 Redux for Multi-page Enterprise UI​

  • Form wizards
  • Multi-step state
  • Async API flows
  • Devtools for debugging complex workflows

4.4 Heavy Calculation Memoization​

const processed = useMemo(() => expensiveWork(data), [data]);


5. Final Recommendations

If you want simplicity and speed → Zustand​

If you have huge global state and need devtools → Redux Toolkit​

If state is mostly local → React built-in hooks​

For performance tuning:​

  • Split components
  • Use memoization selectively
  • Stabilize references with useMemo and useCallback
  • Prefer selectors in Zustand or RTK Query

That's a great request. As a senior architect, here is a best practices document focusing on performance, state management, and memoization in React, designed for intermediate to expert developers.


🚀 React Best Practices for Performance & State Management

This document outlines key strategies and architectural decisions for building highly performant and scalable React applications, focusing on avoiding unnecessary re-renders and selecting the optimal state management tool.

1. Minimizing Unnecessary Re-Renders​

The primary goal of React performance optimization is ensuring that components only render when their necessary inputs (props or state) actually change.

A. The Golden Rule: Use React.memo Strategically​

  • Practice: Always wrap presentational (or "dumb") components that receive props and do not manage their own state in React.memo.
  • Mechanism: React.memo is a Higher-Order Component (HOC) that performs a shallow comparison of the component's previous props and its new props. If the props are shallowly equal, React skips rendering the component.
  • Caveat: If a parent component passes a new object or function reference on every render, React.memo will fail the shallow comparison and the child component will still re-render. This leads directly to the need for memoization hooks (see Section 3).

B. State Colocation (The "Lift State Down" Rule)​

  • Practice: Manage state at the lowest possible level in the component tree.
  • Rationale: When state is defined using useState in a parent component, every time that state changes, the parent and all its children re-render. By moving state down to the component that actually uses it, you isolate the re-render scope, preventing large sections of the application from updating needlessly.

C. Destructure Props Carefully​

  • Practice: When passing large objects or arrays as props, only pass the specific properties the child component needs.
  • Example:
    // ❌ Bad: Causes Re-render if any user property changes
    <UserAvatar user={largeUserObject} />

    // ✅ Good: Only causes Re-render if the name changes
    <UserAvatar userName={largeUserObject.name} />

2. State Management Comparison​

Choosing the right state management tool depends on the complexity and frequency of your application's state updates.

FeatureReact Context + useReducerRedux / Redux Toolkit (RTK)Zustand / Jotai / Recoil
PhilosophyBuilt-in, simple state sharing for medium-sized apps.Centralized, predictable state container.Decentralized, atomic, and minimal global state.
Re-render ScopePropagates broadly. Any component subscribing to the Context re-renders when any part of the Context value changes.Optimized. Uses selectors and middleware (reselect) to ensure components only re-render when the specific data they select changes.Optimized. Components only re-render when the specific slice of state they subscribe to changes, even if it's deeply nested.
BoilerplateLow (only context provider/consumer needed).High (actions, reducers, constants, thunks, store config). RTK reduces this significantly.Very Low. Minimal boilerplate; functions like a global useState.
Ideal ScenarioTheming, internationalization, or infrequent global state (e.g., current user ID).Large, complex applications requiring data normalization, middleware, complex debugging, and persistent history (time-travel debugging).Micro-frontends, small/medium applications, or managing high-frequency state updates with maximum efficiency.

Architectural Recommendation: The Hybrid Approach​

  • Use Zustand or Jotai for High-Frequency Global State (e.g., streaming chat data, animation state, or modal control) due to its minimal rendering overhead.
  • Use React Context for Infrequent UI State (e.g., theme, language settings).
  • Avoid a single massive Redux store unless the application's complexity explicitly requires centralized data normalization and persistence.

3. Deep Dive into Memoization Hooks​

The following hooks are necessary to prevent the issues created by passing non-primitive values (objects, arrays, or functions) down to components wrapped in React.memo.

A. useMemo​

FeatureDescription
PurposeMemoizes a computed value. It caches the result of a function and only re-runs the function when one of its dependencies changes.
Syntaxconst memoizedValue = useMemo(() => expensiveFunction(a, b), [a, b]);
Real-World ScenarioHeavy Computation: Calculating a user's filtered transaction history, complex charting data, or deep filtering/sorting of a large list that takes time.
Anti-PatternDo not use useMemo to memoize simple operations (e.g., a + b). The overhead of the hook itself often outweighs the cost of the simple calculation.

B. useCallback​

FeatureDescription
PurposeMemoizes a function instance. It returns the same function reference across renders unless one of its dependencies changes.
Syntaxconst memoizedHandler = useCallback((e) => handler(e, a), [a]);
Real-World ScenarioPassing functions to React.memo Children: Use this hook when passing event handlers (like onClick, onChange) down to child components that are wrapped in React.memo. This ensures the child component recognizes the handler as the same prop and avoids re-rendering.
Anti-PatternDo not use useCallback unless the function is being passed as a prop to a component that uses React.memo or is a dependency of another hook (like useEffect).

C. The Relationship: The Memoization Cascade​

The three tools work together to manage the rendering cascade :

  1. The Parent Component renders.
  2. useMemo ensures complex objects/values remain the same.
  3. useCallback ensures function references remain the same.
  4. The child component, wrapped in React.memo, receives the same prop references as the last render.
  5. React.memo performs the shallow comparison and successfully skips the re-render.

A fundamental question in optimizing React performance! The difference "before" and "after" using React.memo, useMemo, and useCallback is about control over the rendering lifecycle and preventing unnecessary work.

💡 The Core Concept: Referential Equality​

Before diving into the hooks, it's essential to understand the underlying problem: In JavaScript, objects, arrays, and functions are reference types.

  • When a parent component re-renders, any object or function created inside it (even if logically identical) is given a new memory address (a new reference).
  • If this new reference is passed down as a prop to a child component, React perceives it as a change, forcing the child to re-render, even if the content hasn't changed.

The three memoization tools work to preserve those references, giving React the signal to skip unnecessary updates.


1. React.memo (Component Optimization)​

React.memo is a Higher-Order Component (HOC) used to optimize function components.

FeatureBefore React.memoAfter React.memo
RenderingThe component renders every time its parent renders, regardless of whether its props change.The component performs a shallow comparison of the new props against the previous props. If the props are shallowly equal (same values for primitives, same references for objects/functions), the render is skipped.
Use CaseComponent is simple or props change frequently.Component is "pure" (output depends only on props) and the render logic is expensive or the component is deeply nested in the tree.
ResultWasted CPU cycles, slow user interface (especially if there are many instances).Reduced rendering cycles, faster updates, lower CPU usage.

Example​

A child component wrapped in React.memo will only re-render if its props (e.g., title, count) are different from the last render.


2. useMemo (Value Optimization)​

useMemo is a Hook used to cache the result of an expensive computation or a reference-type value (object/array).

FeatureBefore useMemoAfter useMemo
Value CreationThe expensive function runs on every render. The array or object it returns is created with a new reference on every render.The function runs only when its dependency array changes. The computed value and its reference are cached and reused on subsequent renders.
DependenciesNot applicable; computation always runs.The function is dependent on the values listed in the dependency array ([a, b]).
ResultHigh CPU usage and, more importantly, causes unnecessary re-renders in child components that receive the new object/array reference.Performance gain (by skipping computation) and stability (by providing a consistent reference to children wrapped in React.memo).

Real-World Scenario​

Calculating a complex derivative or filtering a list of 5,000 items. If the filtering criteria haven't changed, the list doesn't need to be re-filtered.


3. useCallback (Function Optimization)​

useCallback is a Hook used to cache the function instance itself.

FeatureBefore useCallbackAfter useCallback
Function ReferenceThe function is redefined, generating a new reference on every render.The same function instance and its memory address are returned on every render unless its dependency array changes.
DependenciesNot applicable; function is always new.The function is dependent on the values listed in the dependency array ([c, d]).
ResultCauses unnecessary re-renders in children wrapped in React.memo because the child sees a "new" function prop.Stability by providing a consistent reference, allowing React.memo in the child component to work correctly.

Real-World Scenario​

Passing an onClick or onChange handler to a highly optimized child button component. If the handler is wrapped in useCallback, the button component will not re-render unnecessarily when the parent renders.

Managing Environment-Specific Logging and Configuration in a Vite React Application

· 阅读需 3 分钟
  1. How to show console logs according to the environment.
  2. How to load environment variables in your application.
  3. How to load the correct environment file (with Vite or Yarn).
  4. How to start the application with the production build.

1. Show Console Logs According to the Environment​

To ensure that console.log, console.warn, and console.error only work in specific environments (e.g., test mode), you can create a utility module that conditionally logs based on the environment.

Example: logUtil.ts​

const isTestEnv = import.meta.env.VITE_ENV === 'test';

const logUtil = {
log: <T>(...args: T[]) => {
if (isTestEnv) {
console.log(...args);
}
},
warn: <T>(...args: T[]) => {
if (isTestEnv) {
console.warn(...args);
}
},
error: <T>(...args: T[]) => {
if (isTestEnv) {
console.error(...args);
}
},
};

export default logUtil;

Explanation:​

  • Environment Check: The isTestEnv variable checks if the VITE_ENV environment variable is set to "test".
  • Conditional Logging: The logUtil methods (log, warn, error) only execute console statements if the environment is test.
  • Type Safety: The utility uses TypeScript generics (<T>) to ensure type safety for the logged arguments.

Usage:​

import logUtil from './utils/logUtil';

logUtil.log("This will only log in test mode");
logUtil.warn("This warning will only appear in test mode");
logUtil.error("This error will only appear in test mode");

2. Load Environment Variables in Your Application​

Vite automatically exposes environment variables prefixed with VITE_ to your application via import.meta.env. To use environment-specific variables:

Example: .env.test​

VITE_ENV=test
VITE_API_URL=https://api.test.example.com

Accessing Environment Variables:​

const apiUrl = import.meta.env.VITE_API_URL;
console.log(apiUrl); // Outputs: https://api.test.example.com

Rules:​

  • Prefix all environment variables with VITE_ (e.g., VITE_ENV, VITE_API_URL).
  • Access them in your application using import.meta.env.

3. Load the Correct Environment File (with Vite or Yarn)​

Vite loads environment variables from .env files based on the mode specified during the build or development process.

Environment Files:​

  • .env: Default environment file (loaded in all modes).
  • .env.test: Loaded when the mode is test.
  • .env.production: Loaded when the mode is production.

Specifying the Mode:​

  • During Development:
    yarn dev --mode test
  • During Build:
    yarn build --mode test

Example Workflow:​

  1. Create a .env.test file:

    VITE_ENV=test
    VITE_API_URL=https://api.test.example.com
  2. Build the application in test mode:

    yarn build --mode test
  3. Vite will load the .env.test file and expose its variables via import.meta.env.


4. Start the Application with the Build​

After building your application, you need to serve the production files. Use a static server like serve or Vite's built-in preview command.

Option 1: Using serve​

  1. Install serve globally or locally:

    yarn global add serve

    Or:

    yarn add serve
  2. Serve the production build:

    serve -s dist
    • The -s flag ensures all routes fall back to index.html (useful for SPAs).
    • The dist directory is the default output directory for Vite builds.
  3. Access the application at http://localhost:3000.

Option 2: Using Vite's Preview Command​

  1. Add a preview script to your package.json:

    "scripts": {
    "build": "vite build",
    "preview": "vite preview"
    }
  2. Build the application:

    yarn build --mode test
  3. Start the preview server:

    yarn preview
    • This serves the production build at http://localhost:4173 (or another port if specified).

Summary​

  1. Environment-Specific Logging:

    • Use a utility like logUtil.ts to conditionally log based on the environment.
  2. Loading Environment Variables:

    • Prefix variables with VITE_ and access them via import.meta.env.
  3. Loading the Correct Environment File:

    • Use the --mode flag with yarn dev or yarn build to load the appropriate .env file.
  4. Starting the Application with the Build:

    • Serve the production build using serve or Vite's preview command.

Deep Dive into the Hook in React

· 阅读需 6 分钟

What is useRef?​

useRef is a hook provided by React that allows you to:

  1. Persist a mutable value across renders without triggering re-renders.
  2. Access a DOM element directly.
  3. Store values similar to an instance variable in class components.

Syntax​

const refContainer = useRef(initialValue);
  • refContainer is an object with a current property.
  • initialValue is the initial value assigned to current.

Textual diagram of a useRef object:

useRef
|
|--- current: <initialValue>

Scenarios and Use Cases​

1. Accessing DOM Elements​

useRef is commonly used to directly access DOM elements. In class components, this was done using React.createRef().

Example:​

import React, { useRef } from 'react';

const FocusInput = () => {
const inputRef = useRef(null);

const handleFocus = () => {
if (inputRef.current) {
inputRef.current.focus(); // Directly focus the input element
}
};

return (
<div>
<input ref={inputRef} type="text" placeholder="Click the button to focus" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
};

export default FocusInput;

Sequence Diagram:

User clicks the "Focus Input" button
|
|--- `handleFocus` is invoked
|
|--- `inputRef.current.focus()` focuses the input element

2. Persisting Values Without Re-Renders​

Unlike useState, updating a useRef value does not trigger a re-render.

Example:​

import React, { useRef, useState } from 'react';

const Counter = () => {
const renderCount = useRef(0);
const [count, setCount] = useState(0);

const increment = () => {
setCount(count + 1);
};

renderCount.current += 1;

return (
<div>
<p>Count: {count}</p>
<p>Component rendered {renderCount.current} times</p>
<button onClick={increment}>Increment</button>
</div>
);
};

export default Counter;

Textual Diagram of State vs Ref:

useState (Triggers Re-render):
state = count: 0 -> render -> state = count: 1 -> render

useRef (No Re-render):
ref = renderCount: 1 -> render -> ref = renderCount: 2 -> no re-render

3. Storing Mutable Values​

When working with mutable values, useRef can store data that changes over time without impacting the component lifecycle.

Example:​

import React, { useRef } from 'react';

const Stopwatch = () => {
const timerId = useRef(null);
const startTime = useRef(null);

const startTimer = () => {
startTime.current = Date.now();
timerId.current = setInterval(() => {
console.log("Elapsed time:", Date.now() - startTime.current);
}, 1000);
};

const stopTimer = () => {
clearInterval(timerId.current);
timerId.current = null;
};

return (
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
};

export default Stopwatch;

Sequence Diagram:

User clicks "Start"
|
|--- `startTimer` invoked
|
|--- `startTime.current` set to current timestamp
|--- `timerId.current` stores interval ID

User clicks "Stop"
|
|--- `stopTimer` invoked
|
|--- `clearInterval(timerId.current)` stops the timer

4. Avoiding Closure Pitfalls​

In functional components, closures can lead to stale values being captured. useRef can prevent this by providing a mutable reference.

Example:​

import React, { useState, useRef } from 'react';

const CounterWithRef = () => {
const countRef = useRef(0);
const [count, setCount] = useState(0);

const increment = () => {
countRef.current += 1; // Updates ref value
setCount(countRef.current); // Updates state
};

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};

export default CounterWithRef;

When to Use useRef​

  • Accessing DOM elements.
  • Storing mutable values that persist across renders.
  • Avoiding re-renders caused by state updates.
  • Managing timers, intervals, or external libraries.

Common Pitfalls​

1. Overusing useRef​

Avoid using useRef for state that should trigger a re-render. Use useState or useReducer instead.

2. Directly Manipulating DOM​

While useRef can access DOM elements, it’s generally better to rely on React’s declarative approach.


Conclusion​

The useRef hook is versatile and indispensable for managing references and mutable values. By understanding its use cases and limitations, you can write cleaner, more efficient React components.


Here's an updated article snippet that includes the scenario where useRef is used with useEffect to ensure that changes to the referenced value do not trigger useEffect, but the effect can still access the latest value of the reference.


Using useRef with useEffect to Access the Latest Value Without Re-triggering​

One of the powerful features of useRef is that it provides a mutable object that does not trigger re-renders when its value changes. This characteristic makes it an excellent tool for scenarios where you need to access the latest value inside a useEffect but do not want the useEffect to re-run whenever the value changes.

Why Use useRef in This Scenario?​

When a state variable is updated, it triggers a re-render, and the useEffect with that state as a dependency is re-executed. However, in some cases, you may want to:

  1. Access the latest value inside the useEffect.
  2. Avoid re-triggering the useEffect when the value changes.

This is where useRef comes in handy.


Code Example: Accessing the Latest Value Without Re-triggering useEffect​

import React, { useState, useEffect, useRef } from "react";

const TimerComponent = () => {
const [isRunning, setIsRunning] = useState(false); // Controls if the timer is running
const countRef = useRef(0); // Tracks the count value
const intervalRef = useRef<NodeJS.Timer | null>(null); // Tracks the interval ID

// Start the timer
const startTimer = () => {
if (!intervalRef.current) {
intervalRef.current = setInterval(() => {
countRef.current += 1; // Update the countRef without causing a re-render
console.log("Current count:", countRef.current); // Always prints the latest count
}, 1000);
setIsRunning(true);
}
};

// Stop the timer
const stopTimer = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
setIsRunning(false);
}
};

// Example: Access the latest value inside useEffect without adding dependencies
useEffect(() => {
const logLatestCount = () => {
console.log("Timer stopped. Latest count value:", countRef.current);
};

if (!isRunning) {
logLatestCount(); // Logs the latest count value without needing countRef as a dependency
}

return () => {
if (intervalRef.current) clearInterval(intervalRef.current); // Cleanup
};
}, [isRunning]); // Dependency only on isRunning, but we can still access countRef.current

return (
<div>
<h1>Count: {countRef.current}</h1> {/* Ref does not trigger re-renders */}
<button onClick={startTimer} disabled={isRunning}>
Start
</button>
<button onClick={stopTimer} disabled={!isRunning}>
Stop
</button>
</div>
);
};

export default TimerComponent;

Sequence Breakdown​

  1. Initial Render:

    • The countRef is initialized to 0, and the intervalRef is null.
  2. Start Timer (startTimer):

    • Sets up a timer with setInterval.
    • Updates countRef.current every second without causing re-renders.
    • isRunning is updated, which triggers a re-render to disable the "Start" button.
  3. Stop Timer (stopTimer):

    • Clears the interval and resets intervalRef to null.
    • Logs the latest value of countRef.current using useEffect because isRunning changes.
  4. Access Latest Value in useEffect:

    • Even though countRef is not a dependency, useEffect can access its latest value because useRef does not reinitialize between renders.

Advantages of Using useRef in This Scenario​

  • Avoiding Re-renders: Unlike useState, updates to useRef do not trigger re-renders, making it perfect for frequently updated values like a timer count.
  • Accessing Latest Value in Effects: The latest value in useRef is always accessible, even in effects, without adding it as a dependency.

Textual Diagram: How useRef and useEffect Work Together​

[Initial Render]
|
|--> useRef initialized: countRef = { current: 0 }
|
[Timer Starts (setInterval)]
|
|--> countRef.current updated every second
| (NO re-renders triggered)
|
[useEffect Triggered on isRunning Change]
|
|--> Access countRef.current to log the latest value
| (No dependency needed for countRef)
|
[Timer Stops]
|
|--> useEffect logs latest countRef.current value

Deep Dive into Google Maps Overlay Types with React + TypeScript

· 阅读需 8 分钟
  1. Introduction to Google Maps Overlays
  2. Markers
  3. Polygons
  4. Polylines
  5. Circles
  6. Rectangles
  7. InfoWindows
  8. GroundOverlay
  9. Custom Overlays
  10. Conclusion

Introduction to Google Maps Overlays​

Overlays are graphical elements that you can add to a Google Map to represent data or highlight specific areas. Google Maps supports the following overlay types:

  • Markers: Represent points of interest.
  • Polygons: Represent closed shapes with multiple vertices.
  • Polylines: Represent lines with multiple vertices.
  • Circles: Represent circular areas.
  • Rectangles: Represent rectangular areas.
  • InfoWindows: Display information about a specific location when a marker is clicked.
  • GroundOverlay: Displays an image or a video over a defined geographical area.
  • Custom Overlays: Allows developers to create their own custom overlays using HTML elements and JavaScript.

Markers​

Markers are used to represent points of interest on the map. Google Maps provides two types of markers:

  • Basic Marker: The traditional marker with a default icon.
  • AdvancedMarkerElement: A customizable marker with support for custom icons and content.

Basic Marker​

Here’s how to create a basic marker:

import React, { useEffect, useRef } from "react";

const BasicMarker: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Add a basic marker
new google.maps.Marker({
position: { lat: 37.7749, lng: -122.4194 },
map: mapRef.current,
title: "San Francisco",
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default BasicMarker;

Custom Marker with AdvancedMarkerElement​

The AdvancedMarkerElement allows you to create highly customizable markers. Here’s an example:

import React, { useEffect, useRef } from "react";

const CustomMarker: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Create a custom marker
const pinElement = document.createElement("div");
pinElement.innerHTML = "📍"; // Custom icon
pinElement.style.fontSize = "24px";

new google.maps.marker.AdvancedMarkerElement({
position: { lat: 37.7749, lng: -122.4194 },
map: mapRef.current,
content: pinElement,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default CustomMarker;

Polygons​

Polygons are used to represent closed shapes with multiple vertices. You can customize their appearance and handle user interactions.

Drawing a Polygon​

Here’s how to draw a polygon:

import React, { useEffect, useRef } from "react";

const PolygonOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the polygon's path
const polygonCoords = [
{ lat: 37.7749, lng: -122.4194 },
{ lat: 37.7849, lng: -122.4294 },
{ lat: 37.7949, lng: -122.4094 },
];

// Draw the polygon
new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default PolygonOverlay;

Handling Polygon Events​

You can handle events like click, mouseover, and mouseout on polygons:

const polygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});

polygon.addListener("click", (event: google.maps.PolyMouseEvent) => {
console.log("Polygon clicked at:", event.latLng);
});

Polylines​

Polylines are used to represent lines with multiple vertices. They are useful for drawing routes or paths.

Drawing a Polyline​

Here’s how to draw a polyline:

import React, { useEffect, useRef } from "react";

const PolylineOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the polyline's path
const polylineCoords = [
{ lat: 37.7749, lng: -122.4194 },
{ lat: 37.7849, lng: -122.4294 },
{ lat: 37.7949, lng: -122.4094 },
];

// Draw the polyline
new google.maps.Polyline({
path: polylineCoords,
strokeColor: "#0000FF",
strokeOpacity: 1.0,
strokeWeight: 4,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default PolylineOverlay;

Handling Polyline Events​

You can handle events like click on polylines:

const polyline = new google.maps.Polyline({
path: polylineCoords,
strokeColor: "#0000FF",
strokeOpacity: 1.0,
strokeWeight: 4,
map: mapRef.current,
});

polyline.addListener("click", (event: google.maps.PolyMouseEvent) => {
console.log("Polyline clicked at:", event.latLng);
});

Circles​

Circles are used to represent circular areas on the map. You can customize their radius, color, and opacity.

Drawing a Circle​

Here’s how to draw a circle:

import React, { useEffect, useRef } from "react";

const CircleOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Draw the circle
new google.maps.Circle({
center: { lat: 37.7749, lng: -122.4194 },
radius: 1000, // Radius in meters
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default CircleOverlay;

Handling Circle Events​

You can handle events like click on circles:

const circle = new google.maps.Circle({
center: { lat: 37.7749, lng: -122.4194 },
radius: 1000,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});

circle.addListener("click", (event: google.maps.MapMouseEvent) => {
console.log("Circle clicked at:", event.latLng);
});

Rectangles​

Rectangles are used to represent rectangular areas on the map. You can customize their bounds, color, and opacity.

Drawing a Rectangle​

Here’s how to draw a rectangle:

import React, { useEffect, useRef } from "react";

const RectangleOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the rectangle's bounds
const rectangleBounds = {
north: 37.7849,
south: 37.7649,
east: -122.4094,
west: -122.4294,
};

// Draw the rectangle
new google.maps.Rectangle({
bounds: rectangleBounds,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.35,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default RectangleOverlay;

Handling Rectangle Events​

You can handle events like click on rectangles:

const rectangle = new google.maps.Rectangle({
bounds: rectangleBounds,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.35,
map: mapRef.current,
});

rectangle.addListener("click", (event: google.maps.MapMouseEvent) => {
console.log("Rectangle clicked at:", event.latLng);
});

InfoWindows​

InfoWindows are used to display additional information about a location on the map. They are typically attached to markers but can also be used independently.

Adding an InfoWindow​

Here’s how to add an InfoWindow to a marker:

import React, { useEffect, useRef } from "react";

const InfoWindowExample: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Create a marker
const marker = new google.maps.Marker({
position: { lat: 37.7749, lng: -122.4194 },
map: mapRef.current,
title: "San Francisco",
});

// Create an InfoWindow
const infoWindow = new google.maps.InfoWindow({
content: "<h3>San Francisco</h3><p>Welcome to the Golden City!</p>",
});

// Attach the InfoWindow to the marker
marker.addListener("click", () => {
infoWindow.open(mapRef.current, marker);
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default InfoWindowExample;

Handling InfoWindow Events​

You can handle events like closeclick on InfoWindows:

infoWindow.addListener("closeclick", () => {
console.log("InfoWindow closed");
});

GroundOverlay​

GroundOverlays are used to overlay images (e.g., maps, satellite imagery) on specific areas of the map.

Adding a GroundOverlay​

Here’s how to add a GroundOverlay:

import React, { useEffect, useRef } from "react";

const GroundOverlayExample: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the bounds for the GroundOverlay
const bounds = {
north: 37.7849,
south: 37.7649,
east: -122.4094,
west: -122.4294,
};

// Add a GroundOverlay
new google.maps.GroundOverlay(
"https://www.example.com/image.png", // URL of the image
bounds,
{
map: mapRef.current,
opacity: 0.5, // Set the opacity of the overlay
}
);
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default GroundOverlayExample;

Custom Overlays​

Custom Overlays allow you to create fully custom overlays using HTML, CSS, and JavaScript. This is useful for adding complex UI elements to the map.

Creating a Custom Overlay​

Here’s how to create a custom overlay:

import React, { useEffect, useRef } from "react";

class CustomOverlay extends google.maps.OverlayView {
private div: HTMLElement | null = null;

constructor(
private position: google.maps.LatLng,
private content: string
) {
super();
}

onAdd(): void {
this.div = document.createElement("div");
this.div.style.position = "absolute";
this.div.style.backgroundColor = "white";
this.div.style.border = "1px solid black";
this.div.style.padding = "10px";
this.div.innerHTML = this.content;

const panes = this.getPanes();
if (panes) {
panes.overlayLayer.appendChild(this.div);
}
}

draw(): void {
if (this.div) {
const projection = this.getProjection();
const point = projection.fromLatLngToDivPixel(this.position);

if (point) {
this.div.style.left = `${point.x}px`;
this.div.style.top = `${point.y}px`;
}
}
}

onRemove(): void {
if (this.div) {
this.div.parentNode?.removeChild(this.div);
this.div = null;
}
}
}

const CustomOverlayExample: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Create a custom overlay
const overlay = new CustomOverlay(
new google.maps.LatLng(37.7749, -122.4194),
"<h3>Custom Overlay</h3><p>This is a custom overlay!</p>"
);

// Add the overlay to the map
overlay.setMap(mapRef.current);
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default CustomOverlayExample;

References:​

Setting Up Google Maps in React​

Before diving into overlays, ensure you have set up the Google Maps JavaScript API in your React application. Follow the steps in the Google Maps Documentation to obtain your API key and include it in your project.

Component Communication in React: A Comprehensive Guide

· 阅读需 4 分钟

Table of Contents​

  1. Props (Parent to Child)
  2. Callback Functions (Child to Parent)
  3. React Context API (Global State)
  4. State Management Libraries (Redux, Zustand, etc.)
  5. Refs (Direct DOM Manipulation or Between Components)
  6. Event Emitters (Custom Events)
  7. URL Parameters (React Router)
  8. Third-Party Pub/Sub Libraries (e.g., PubSubJS, RxJS)
  9. API/Server Communication

1. Props (Parent to Child)​

Props allow data to flow from a parent component to a child component.

Example Code:​

function Parent() {
const message = "Hello from Parent!";
return <Child message={message} />;
}

function Child({ message }) {
return <p>{message}</p>;
}

Textual Diagram:​

Parent -> Props -> Child

2. Callback Functions (Child to Parent)​

A child component can communicate with its parent by invoking a callback function passed as a prop.

Example Code:​

function Parent() {
const handleChildEvent = (data) => {
console.log("Received from child:", data);
};

return <Child onSend={handleChildEvent} />;
}

function Child({ onSend }) {
return <button onClick={() => onSend("Hello Parent!")}>Send Message</button>;
}

Textual Diagram:​

Child -> Callback Function -> Parent

3. React Context API (Global State)​

The Context API allows you to share data across the component tree without passing props explicitly.

Example Code:​

import React, { createContext, useContext } from 'react';

const MyContext = createContext();

function Parent() {
return (
<MyContext.Provider value="Shared Data">
<Child />
</MyContext.Provider>
);
}

function Child() {
const data = useContext(MyContext);
return <p>{data}</p>;
}

Textual Diagram:​

Parent -> Context Provider -> Child
Context Consumer <- Child

4. State Management Libraries (Redux, Zustand, etc.)​

State management libraries allow you to manage the global state of an application efficiently.

Example Code (Redux):​

import { createStore } from "redux";
import { Provider, useDispatch, useSelector } from "react-redux";

const reducer = (state = { count: 0 }, action) => {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
default:
return state;
}
};

const store = createStore(reducer);

function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();

return (
<div>
<p>{count}</p>
<button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
</div>
);
}

function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}

Textual Diagram:​

State -> Redux Store -> Component
Dispatch Action <- Component

5. Refs (Direct DOM Manipulation or Between Components)​

Refs allow direct interaction with DOM elements or instances of other components.

Example Code:​

function Parent() {
const childRef = useRef();

const handleClick = () => {
childRef.current.sayHello();
};

return (
<>
<Child ref={childRef} />
<button onClick={handleClick}>Call Child Method</button>
</>
);
}

const Child = React.forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
sayHello: () => {
alert("Hello from Child!");
},
}));
return <p>Child Component</p>;
});

Textual Diagram:​

Parent -> Ref -> Child Method

6. Event Emitters (Custom Events)​

Custom events can be used to communicate between loosely coupled components.

Example Code:​

import { EventEmitter } from "events";

const eventEmitter = new EventEmitter();

function ComponentA() {
const sendMessage = () => {
eventEmitter.emit("message", "Hello from ComponentA!");
};

return <button onClick={sendMessage}>Send Message</button>;
}

function ComponentB() {
useEffect(() => {
eventEmitter.on("message", (data) => {
console.log("Received:", data);
});

return () => {
eventEmitter.removeAllListeners("message");
};
}, []);

return <p>Listening for messages...</p>;
}

Textual Diagram:​

ComponentA -> Event Emitter -> ComponentB

Comparison with Callback-Based Approach​

AspectEventEmitterCallback-Based
CouplingDecoupled (uses events)Tightly coupled (passes callbacks)
ScalabilityHighly scalable for multiple eventsLess scalable for many events
ComplexitySlightly more complex (requires setup)Simpler (direct function calls)
ReusabilityReusable across the applicationLimited to specific components
Memory ManagementRequires cleanup (off method)Automatically cleaned up by React

7. URL Parameters (React Router)​

React Router enables communication via route parameters or query strings.

Example Code:​

import { BrowserRouter as Router, Route, useParams } from "react-router-dom";

function Parent() {
return (
<Router>
<Route path="/user/:id" component={Child} />
</Router>
);
}

function Child() {
const { id } = useParams();
return <p>User ID: {id}</p>;
}

Textual Diagram:​

URL -> Route Params -> Child

8. Third-Party Pub/Sub Libraries (e.g., PubSubJS, RxJS)​

Libraries like RxJS or PubSubJS enable event-based communication.

Example Code (RxJS):​

import { Subject } from "rxjs";

const subject = new Subject();

function ComponentA() {
const sendMessage = () => {
subject.next("Hello from ComponentA!");
};

return <button onClick={sendMessage}>Send Message</button>;
}

function ComponentB() {
useEffect(() => {
const subscription = subject.subscribe((data) => {
console.log("Received:", data);
});

return () => subscription.unsubscribe();
}, []);

return <p>Listening for messages...</p>;
}

Textual Diagram:​

ComponentA -> Subject -> ComponentB

9. API/Server Communication​

Components can exchange data through a server or API.

Example Code:​

function Parent() {
const [data, setData] = useState(null);

useEffect(() => {
fetch("/api/data")
.then((response) => response.json())
.then((data) => setData(data));
}, []);

return <Child data={data} />;
}

function Child({ data }) {
return <p>{data ? `Fetched Data: ${data}` : "Loading..."}</p>;
}

Textual Diagram:​

Server <- Fetch API -> Parent -> Props -> Child

Deep Dive Developing a React TypeScript Application for Google Maps

· 阅读需 4 分钟

Choosing the Right React Library for Google Maps​

There are two popular libraries for integrating Google Maps into React applications:

1. react-google-maps-api​

Features:​

  • Built with TypeScript support out of the box.
  • Highly optimized for performance.
  • Provides detailed type definitions for Google Maps API objects and events.
  • Supports SSR (Server-Side Rendering) and lazy loading of the Google Maps API.

Pros:​

  • Excellent TypeScript support.
  • Well-maintained and frequently updated.
  • Extensive documentation and examples.

Cons:​

  • Requires a steeper learning curve due to its focus on optimization and customization.

2. @react-google-maps/api​

Features:​

  • A modern, lightweight alternative to react-google-maps-api.
  • Provides a simple and intuitive API for Google Maps integration.
  • Supports TypeScript.
  • Optimized for performance with lazy loading and minimal re-renders.

Pros:​

  • Lightweight and fast.
  • Easy to use with minimal boilerplate.
  • Excellent TypeScript support.

Cons:​

  • Less mature compared to react-google-maps-api.
  • Fewer community resources and examples.

Recommendation:​

For most applications, react-google-maps-api is the preferred choice due to its robust TypeScript support and active development. However, for simpler projects, @react-google-maps/api may be sufficient.


Key Considerations for Google Maps Event Handling​

1. Event Compatibility​

Google Maps provides different event types for various objects. Ensure the event you are attaching is supported by the target object. For example:

  • Polygon and Polyline support the rightclick event.
  • MVCArray does not support rightclick, making it challenging to attach such an event directly to a vertex.

Tip:​

Always consult the Google Maps JavaScript API documentation to verify event compatibility.

2. Modern GUI Concepts​

When building interactions, remember:

  • Many devices, such as iPads and smartphones, lack traditional mouse functionality.
  • Avoid relying on events like rightclick for core features. Instead, design user interfaces with touch and gesture interactions in mind.

3. Event Attributes​

Google Maps events like MapMouseEvent or PolyMouseEvent lack a button attribute to identify the mouse button used. Instead, use the domEvent property for this information.

Example:​

polygon.addListener("mousedown", (event: google.maps.PolyMouseEvent) => {
const mouseEvent = event.domEvent as MouseEvent;
if (mouseEvent.button === 0) {
console.log("Left mouse button clicked");
} else if (mouseEvent.button === 2) {
console.log("Right mouse button clicked");
}
});

Example: Attaching Event Listeners to Map Objects​

Below is a React component for managing drawing tools and attaching event listeners to polygons and polylines.

import React, { useEffect, useRef, useCallback, useState } from "react";

const addPathListeners = (path: google.maps.MVCArray<google.maps.LatLng>) => {
path.forEach((_, index) => {
google.maps.event.addListener(path, "mouseover", () => {
console.log(`Mouse over vertex ${index}`);
document.body.style.cursor = "pointer";
});

google.maps.event.addListener(path, "mouseout", () => {
document.body.style.cursor = "default";
});
});
};

const attachListenersToEditablePolygon = (polygon: google.maps.Polygon) => {
const path = polygon.getPath();

addPathListeners(path);

google.maps.event.addListener(path, "insert_at", () => addPathListeners(path));
google.maps.event.addListener(path, "remove_at", () => addPathListeners(path));
google.maps.event.addListener(path, "set_at", () => addPathListeners(path));
};

const MapDrawingManager: React.FC<{ mapRef: React.RefObject<google.maps.Map | null> }> = ({ mapRef }) => {
const drawingManagerRef = useRef<google.maps.drawing.DrawingManager | null>(null);

const handlePolygonComplete = useCallback((polygon: google.maps.Polygon) => {
polygon.setOptions({
fillColor: "#0000FF80",
strokeColor: "#0000FF",
strokeWeight: 4,
editable: true,
});

attachListenersToEditablePolygon(polygon);
}, []);

useEffect(() => {
if (mapRef.current && !drawingManagerRef.current) {
const manager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
});

google.maps.event.addListener(manager, "polygoncomplete", handlePolygonComplete);

manager.setMap(mapRef.current);
drawingManagerRef.current = manager;

return () => {
manager.setMap(null);
drawingManagerRef.current = null;
};
}
}, [mapRef, handlePolygonComplete]);

return null;
};

export default MapDrawingManager;

Migrating from google.maps.marker to advancedmarker​

Google has deprecated the google.maps.marker class in favor of the new advancedmarker class. The advancedmarker class offers improved performance and additional features, making it the recommended choice for new projects.

Key Differences:​

  • Performance: advancedmarker is optimized for better performance, especially in applications with a large number of markers.
  • Features: advancedmarker supports advanced features like custom HTML content and improved event handling.

Migration Steps:​

  1. Update Imports: Replace google.maps.marker with google.maps.advancedmarker.
  2. Refactor Code: Update your code to use the new advancedmarker API. This may involve changes to how you create, configure, and interact with markers.
  3. Test Thoroughly: Ensure that your application works as expected after the migration.

Example:​

// Old way using google.maps.marker
const marker = new google.maps.Marker({
position: { lat: -34.397, lng: 150.644 },
map: mapRef.current,
});

// New way using google.maps.advancedmarker
const advancedMarker = new google.maps.advancedmarker.AdvancedMarker({
position: { lat: -34.397, lng: 150.644 },
map: mapRef.current,
});

Best Practices​

  1. Design for Touch-First: Avoid interactions relying on mouse-specific events like rightclick.
  2. Event Verification: Confirm the compatibility of events with the target object.
  3. TypeScript Usage: Leverage TypeScript for better type safety and developer experience.
  4. Code Modularity: Organize logic into reusable functions, such as addPathListeners.
  5. Migrate to advancedmarker: Update your code to use the new advancedmarker class for better performance and features.

Building a Google Maps Application with React and TypeScript

· 阅读需 3 分钟

Prerequisites​

  • Node.js installed (version 14 or higher).
  • npm or yarn for package management.
  • A Google Cloud Platform (GCP) account to obtain the API Key and set up the Map ID.

Project Setup​

  1. Create a React Application:

    npx create-react-app google-maps-app --template typescript
    cd google-maps-app
  2. Install Required Dependencies:

    npm install @react-google-maps/api
    npm install react-hook-form
  3. Setup Google Cloud Platform:

    • Enable the Maps JavaScript API:
      1. Go to the Google Cloud Console.
      2. Create a new project or select an existing one.
      3. Navigate to APIs & Services > Library and enable the Maps JavaScript API.
    • Generate an API Key:
      1. Go to APIs & Services > Credentials and create an API Key.
      2. Restrict the API Key to ensure security by specifying HTTP referrers (your domain or localhost).
    • Create a Map ID:
      1. Go to Google Maps Platform > Maps > Map Management.
      2. Create a new Map ID and configure it with desired styles and settings.

Project Structure​

google-maps-app/
├── public/
├── src/
│ ├── components/
│ │ ├── MapContainer.tsx
│ │ ├── SearchBox.tsx
│ ├── App.tsx
│ ├── index.tsx
│ ├── types/
│ │ ├── index.d.ts
│ ├── utils/
│ ├── mapUtils.ts

Coding the Application​

Step 1: Setup TypeScript Types​

Create src/types/index.d.ts to define types for the Google Maps objects:

declare global {
interface Window {
google: any;
}
}

export interface MarkerData {
position: google.maps.LatLngLiteral;
title: string;
}

Step 2: Utility Functions​

Create src/utils/mapUtils.ts to define helper functions:

export const loadGoogleMapsScript = (apiKey: string): Promise<void> => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`;
script.async = true;
script.defer = true;
script.onload = () => resolve();
script.onerror = (e) => reject(e);
document.head.appendChild(script);
});
};

Step 3: Map Container​

Create src/components/MapContainer.tsx:

import React, { useEffect, useRef, useState } from 'react';
import { MarkerData } from '../types';

type MapContainerProps = {
apiKey: string;
mapId: string;
};

const MapContainer: React.FC<MapContainerProps> = ({ apiKey, mapId }) => {
const mapRef = useRef<HTMLDivElement>(null);
const [map, setMap] = useState<google.maps.Map | null>(null);
const [markers, setMarkers] = useState<google.maps.Marker[]>([]);

useEffect(() => {
const initMap = async () => {
try {
await loadGoogleMapsScript(apiKey);
if (mapRef.current) {
const mapInstance = new google.maps.Map(mapRef.current, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
mapId: mapId,
});
setMap(mapInstance);
}
} catch (error) {
console.error('Failed to load Google Maps:', error);
}
};

initMap();
}, [apiKey, mapId]);

const addMarker = (markerData: MarkerData) => {
if (map) {
const marker = new google.maps.marker.AdvancedMarkerElement({
map,
position: markerData.position,
title: markerData.title,
});
setMarkers((prev) => [...prev, marker]);
}
};

return <div ref={mapRef} style={{ width: '100%', height: '500px' }} />;
};

export default MapContainer;

Create src/components/SearchBox.tsx:

import React, { useEffect, useRef } from 'react';

type SearchBoxProps = {
onPlaceSelected: (place: google.maps.places.PlaceResult) => void;
};

const SearchBox: React.FC<SearchBoxProps> = ({ onPlaceSelected }) => {
const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
if (inputRef.current) {
const autocomplete = new google.maps.places.Autocomplete(inputRef.current);
autocomplete.addListener('place_changed', () => {
const place = autocomplete.getPlace();
if (place) {
onPlaceSelected(place);
}
});
}
}, []);

return <input ref={inputRef} type="text" placeholder="Search places..." />;
};

export default SearchBox;

Step 5: Combine Components​

Update src/App.tsx:

import React, { useState } from 'react';
import MapContainer from './components/MapContainer';
import SearchBox from './components/SearchBox';
import { MarkerData } from './types';

const App: React.FC = () => {
const [markers, setMarkers] = useState<MarkerData[]>([]);
const apiKey = 'YOUR_GOOGLE_MAPS_API_KEY';
const mapId = 'YOUR_MAP_ID';

const handlePlaceSelected = (place: google.maps.places.PlaceResult) => {
if (place.geometry?.location) {
const markerData = {
position: {
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
},
title: place.name || '',
};
setMarkers((prev) => [...prev, markerData]);
}
};

return (
<div>
<SearchBox onPlaceSelected={handlePlaceSelected} />
<MapContainer apiKey={apiKey} mapId={mapId} />
</div>
);
};

export default App;

Running the Application​

  1. Replace YOUR_GOOGLE_MAPS_API_KEY and YOUR_MAP_ID in App.tsx with your actual values.
  2. Start the application:
    npm start
  3. Open http://localhost:3000 in your browser.

Deep Dive: Modal Dialog Mechanism in React Applications

· 阅读需 5 分钟

Modal dialogs are a common UI pattern used to display important information, collect user input, or confirm actions. In React applications, implementing a modal dialog involves managing state, rendering the dialog conditionally, and ensuring proper styling and positioning. This article explores the modal dialog mechanism in React, using the popular react-modal library as an example. We'll also provide a complete testing setup to ensure the modal works as expected.


Table of Contents​

  1. Introduction to Modal Dialogs
  2. Key Concepts in Modal Dialogs
  3. Using react-modal in React
  4. Styling and Positioning the Modal
  5. Ensuring Proper Z-Index
  6. Testing Modal Dialogs
  7. Conclusion

1. Introduction to Modal Dialogs​

A modal dialog is a UI component that overlays the main application content, forcing the user to interact with it before continuing. Modal dialogs are commonly used for:

  • Alerts and confirmations
  • Form inputs
  • Loading indicators
  • Error messages

In React, modal dialogs are typically implemented using state to control their visibility and lifecycle.


2. Key Concepts in Modal Dialogs​

a. State Management​

The visibility of a modal dialog is controlled by a boolean state variable (e.g., isOpen). When isOpen is true, the modal is rendered; otherwise, it is hidden.

b. Conditional Rendering​

The modal is rendered conditionally based on the state variable. This ensures that the modal is only added to the DOM when needed.

c. Focus Management​

Modals should trap focus within their content to ensure accessibility. This prevents users from interacting with the background content while the modal is open.

d. Z-Index​

The modal's z-index must be higher than the parent component's z-index to ensure it appears on top of other elements.

e. Escape Key Handling​

Users should be able to close the modal by pressing the Escape key.


3. Using react-modal in React​

react-modal is a popular library for creating accessible and customizable modal dialogs in React. Below is an example of how to use it:

Installation​

npm install react-modal

Example Code​

import React, { useState } from "react";
import Modal from "react-modal";

// Set the app element for accessibility (required by react-modal)
Modal.setAppElement("#root");

const App = () => {
const [isOpen, setIsOpen] = useState(false);

const openModal = () => setIsOpen(true);
const closeModal = () => setIsOpen(false);

return (
<div>
<button onClick={openModal}>Open Modal</button>

<Modal
isOpen={isOpen}
onRequestClose={closeModal}
contentLabel="Example Modal"
style={{
overlay: {
backgroundColor: "rgba(0, 0, 0, 0.5)",
zIndex: 1000, // Ensure the modal is on top
},
content: {
width: "400px",
height: "200px",
margin: "auto",
padding: "20px",
borderRadius: "8px",
boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
},
}}
>
<h2>Modal Title</h2>
<p>This is the modal content.</p>
<button onClick={closeModal}>Close</button>
</Modal>
</div>
);
};

export default App;

4. Styling and Positioning the Modal​

a. Custom Styles​

react-modal allows you to customize the modal's appearance using the style prop. The overlay style controls the background overlay, while the content style controls the modal's content.

b. Centering the Modal​

To center the modal, set the margin property of the content style to auto.

c. Responsive Design​

Use CSS media queries to adjust the modal's size and position for different screen sizes.


5. Ensuring Proper Z-Index​

The z-index property is crucial for ensuring the modal appears on top of other elements. Here's how to handle it:

a. Set a High Z-Index for the Modal​

<Modal
isOpen={isOpen}
style={{
overlay: {
zIndex: 1000, // Higher than other elements
},
}}
/>

b. Ensure Parent Components Have Lower Z-Index​

If the parent component has a high z-index, the modal will not appear on top. For example:

.parent-component {
z-index: 10; /* Lower than the modal's z-index */
}

6. Testing Modal Dialogs​

Testing modal dialogs ensures they work as expected in different scenarios. Below is an example of testing a modal dialog using react-testing-library.

Installation​

npm install @testing-library/react @testing-library/jest-dom

Testing Code​

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Modal from "react-modal";
import App from "./App";

// Mock react-modal
jest.mock("react-modal", () => {
const Modal = ({ isOpen, children }) => (isOpen ? <div>{children}</div> : null);
return Modal;
});

describe("Modal Dialog", () => {
it("opens and closes the modal", () => {
render(<App />);

// Modal should not be visible initially
expect(screen.queryByText("Modal Title")).not.toBeInTheDocument();

// Open the modal
fireEvent.click(screen.getByText("Open Modal"));
expect(screen.getByText("Modal Title")).toBeInTheDocument();

// Close the modal
fireEvent.click(screen.getByText("Close"));
expect(screen.queryByText("Modal Title")).not.toBeInTheDocument();
});
});

7. Conclusion​

Modal dialogs are a powerful tool for enhancing user interaction in React applications. By understanding key concepts like state management, conditional rendering, focus trapping, and z-index, you can create accessible and user-friendly modals. The react-modal library simplifies the process, and proper testing ensures your modals work as expected in all scenarios.


Additional Resources​

Deep Dive into ReactJS Hooks

· 阅读需 5 分钟

React Hooks, introduced in React 16.8, revolutionized functional components by adding state and lifecycle capabilities, enabling a simpler, more powerful way to manage logic within components. This guide will provide a deep dive into React’s core hooks, detailing how they work, the scenarios in which they shine, and best practices for leveraging them effectively.


Introduction to Hooks​

Hooks allow you to use state, lifecycle methods, and other React features without writing a class. They provide a way to reuse logic across components in a more composable and understandable way, helping developers avoid the complex nesting and lifecycle clutter often encountered with higher-order components and render props.

Why Hooks?​

  • Simplify state and side effect management in functional components.
  • Enhance code reuse with custom hooks.
  • Make components cleaner and more readable.

Basic Hooks​

React offers several core hooks that cover common needs such as state, effects, and references.

useState: Managing State in Functional Components​

useState is used to declare state within functional components. It returns an array with two values: the current state and a function to update it.

Syntax:​

const [state, setState] = useState(initialValue);

Practical Scenario: Toggling a Modal​

import React, { useState } from 'react';

function ModalToggle() {
const [isOpen, setIsOpen] = useState(false);

const toggleModal = () => setIsOpen(!isOpen);

return (
<div>
<button onClick={toggleModal}>Toggle Modal</button>
{isOpen && <Modal />}
</div>
);
}

useEffect: Side Effects and Lifecycle Events​

useEffect manages side effects (such as data fetching, subscriptions, or DOM manipulation). It runs after the component renders and accepts a dependency array that controls when it should re-run.

Syntax:​

useEffect(() => {
// effect code here
return () => {
// cleanup code here
};
}, [dependencies]);

Practical Scenario: Fetching Data on Component Load​

import React, { useState, useEffect } from 'react';

function UserList() {
const [users, setUsers] = useState([]);

useEffect(() => {
async function fetchUsers() {
const response = await fetch('/api/users');
const data = await response.json();
setUsers(data);
}

fetchUsers();
}, []); // Empty array means this runs only once, similar to componentDidMount

return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}

Tips:​

  • Cleanup: Return a cleanup function to avoid memory leaks (e.g., unsubscribing from a WebSocket).
  • Dependencies: Use the dependency array to specify when the effect should re-run.

Advanced Hooks​

Beyond the basic hooks, React provides additional hooks for managing more specialized situations.

useContext: Accessing Context Values​

useContext allows components to access and consume context values directly without needing to wrap them in a Consumer.

Syntax:​

const contextValue = useContext(MyContext);

Practical Scenario: Global Theme Management​

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function ThemedButton() {
const theme = useContext(ThemeContext);

return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}

Additional Hooks​

useReducer: Managing Complex State​

useReducer is an alternative to useState for managing complex state transitions, typically in situations where you would use Redux or other state management libraries.

Syntax:​

const [state, dispatch] = useReducer(reducer, initialState);

Practical Scenario: A Counter with Increment/Decrement​

import React, { useReducer } from 'react';

function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<div>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</div>
);
}

useRef: Persistent Mutable References​

useRef creates a persistent reference that doesn’t cause re-renders, making it ideal for storing mutable values like DOM elements.

Syntax:​

const ref = useRef(initialValue);

Practical Scenario: Focusing an Input Element​

import React, { useRef } from 'react';

function TextInputWithFocus() {
const inputRef = useRef(null);

const handleClick = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus the input</button>
</div>
);
}

useMemo: Memoizing Expensive Calculations​

useMemo optimizes performance by memoizing expensive calculations, only recomputing them when dependencies change.

Syntax:​

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Practical Scenario: Filtering a Large List​

import React, { useState, useMemo } from 'react';

function FilterableList({ items }) {
const [query, setQuery] = useState('');

const filteredItems = useMemo(() => {
return items.filter(item => item.toLowerCase().includes(query.toLowerCase()));
}, [items, query]);

return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Filter items" />
<ul>
{filteredItems.map(item => <li key={item}>{item}</li>)}
</ul>
</div>
);
}

Custom Hooks​

Custom hooks are functions that allow you to extract and reuse stateful logic across components. They enable you to abstract complex logic in a cleaner, more maintainable way.

Practical Scenario: A useFetch Hook for Data Fetching​

import { useState, useEffect } from 'react';

function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
async function fetchData() {
setLoading(true);
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
}

fetchData();
}, [url]);

return { data, loading };
}

export default useFetch;

Using useFetch in a Component​

import React from 'react';
import useFetch from './useFetch';

function Users() {
const { data, loading } = useFetch('/api/users');

if (loading) return <p>Loading...</p>;
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}

Error Handling and Best Practices​

Error Handling in Hooks​

  1. Wrap async operations with a try-catch to handle errors gracefully.
  2. Global error boundaries for handling errors in effects or custom hooks (using libraries like react-error-boundary).

Best Practices​

  • Dependency Arrays: Always add dependencies in useEffect and useMemo dependency arrays to avoid stale closures.
  • Avoid Side Effects in Render: Avoid triggering side effects inside render methods to prevent unexpected behavior.

Conclusion​

React Hooks provide powerful, flexible solutions for managing state, effects, and other logic in functional components. Mastering these core hooks, along with custom hooks, enables you to write cleaner, more maintainable code.

With practical examples, error handling tips, and performance optimizations, you’re now equipped to build complex React applications that harness the full power of hooks.

Best Practices for Local Storage Handling in ReactJS

· 阅读需 11 分钟

Introduction​

Local storage is a powerful tool for persisting data in web applications. In ReactJS, local storage can be used to store user preferences, shopping cart items, and other data that needs to persist across sessions. This article will deep dive into best practices for handling local storage in ReactJS with TypeScript, focusing on functional components and the latest version of the tech stack. We will provide real production scenarios with TypeScript code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn.

1. Local Storage Basics​

1.1 Project Setup​

To get started, we need to set up a React project with TypeScript and add the necessary dependencies using Yarn.

Yarn Commands​

# Create a React project with TypeScript template
yarn create react-app local-storage-app --template typescript

# Navigate into the project directory
cd local-storage-app

# Add any additional dependencies if needed (e.g., testing libraries)
yarn add @testing-library/react @testing-library/jest-dom

1.2 Project Folder Structure​

project-root/
├── src/
│ ├── components/
│ │ ├── UserPreferencesComponent.tsx
│ │ ├── ShoppingCartComponent.tsx
│ ├── hooks/
│ │ └── useLocalStorage.ts
│ ├── utils/
│ │ ├── localStorageUtils.ts
│ ├── App.tsx
│ ├── index.tsx
├── tests/
│ ├── components/
│ │ ├── UserPreferencesComponent.test.tsx
│ │ ├── ShoppingCartComponent.test.tsx
│ ├── utils/
│ │ ├── localStorageUtils.test.ts
├── package.json
├── tsconfig.json
├── yarn.lock

2.1 What is Local Storage?​

Local storage is a web storage API that allows you to store key-value pairs in a web browser. It is a synchronous, persistent storage that allows developers to store data client-side. The data stored in local storage persists even after the browser is closed and reopened. Leveraging local storage in React applications with TypeScript can help maintain user state, save preferences, and reduce API calls.

2.2 Local Storage vs Session Storage​

  • Local Storage: Data persists across browser sessions.
  • Session Storage: Data is cleared when the browser session ends (e.g., when the browser is closed).

3. Local Storage Basics​

3.1 Basic API​

Local storage provides a simple API: setItem(), getItem(), and removeItem(). Data stored in local storage is accessible across browser sessions.

// Setting an item
localStorage.setItem('key', 'value');

// Getting an item
const value = localStorage.getItem('key');

// Removing an item
localStorage.removeItem('key');

3.2 Type Safety​

Use TypeScript to ensure type safety when interacting with local storage. Create utility functions or custom hooks in TypeScript to handle type-safe operations.

interface UserPreferences {
theme: string;
notifications: boolean;
}

const setUserPreferences = (preferences: UserPreferences): void => {
setLocalStorageItem('userPreferences', preferences);
};

const getUserPreferences = (): UserPreferences | null => {
return getLocalStorageItem<UserPreferences>('userPreferences');
};

3.3 Error Handling​

Handle errors gracefully when interacting with local storage. Wrap local storage operations in try-catch blocks to handle any potential errors gracefully.

export const setLocalStorageItem = <T>(key: string, value: T): void => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error setting local storage item: ${error}`);
}
};

export const getLocalStorageItem = <T>(key: string): T | null => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (error) {
console.error(`Error getting local storage item: ${error}`);
return null;
}
};

3.4 Data Serialization​

Ensure that data is properly serialized and deserialized when storing and retrieving from local storage. Always serialize complex data structures as strings using JSON.stringify().

export const setLocalStorageItem = <T>(key: string, value: T): void => {
localStorage.setItem(key, JSON.stringify(value));
};

export const getLocalStorageItem = <T>(key: string): T | null => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
};

3.5 Expiration Handling​

Implement expiration handling for local storage items to ensure that stale data is not used.

interface ExpirableItem<T> {
value: T;
expiration: number;
}

export const setExpirableLocalStorageItem = <T>(key: string, value: T, expirationInMinutes: number): void => {
const expiration = new Date().getTime() + expirationInMinutes * 60 * 1000;
const item: ExpirableItem<T> = { value, expiration };
setLocalStorageItem(key, item);
};

export const getExpirableLocalStorageItem = <T>(key: string): T | null => {
const item = getLocalStorageItem<ExpirableItem<T>>(key);
if (item && item.expiration > new Date().getTime()) {
return item.value;
}
removeLocalStorageItem(key);
return null;
};

4. Best Practices​

4.1 Encapsulating Local Storage Access​

Encapsulate local storage logic inside React hooks or service functions to keep components clean. Encapsulate local storage access within utility functions to avoid code duplication and improve maintainability.

export const setLocalStorageItem = <T>(key: string, value: T): void => {
localStorage.setItem(key, JSON.stringify(value));
};

export const getLocalStorageItem = <T>(key: string): T | null => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
};

export const removeLocalStorageItem = (key: string): void => {
localStorage.removeItem(key);
};

5 More Scenarios​

5.1 Scenario 1: User Preferences​

import React, { useState, useEffect } from 'react';
import { setUserPreferences, getUserPreferences } from './localStorageUtils';

interface UserPreferences {
theme: string;
notifications: boolean;
}

const UserPreferencesComponent: React.FC = () => {
const [preferences, setPreferences] = useState<UserPreferences | null>(null);

useEffect(() => {
const storedPreferences = getUserPreferences();
if (storedPreferences) {
setPreferences(storedPreferences);
}
}, []);

const handleThemeChange = (theme: string) => {
const updatedPreferences = { ...preferences, theme } as UserPreferences;
setUserPreferences(updatedPreferences);
setPreferences(updatedPreferences);
};

const handleNotificationsChange = (notifications: boolean) => {
const updatedPreferences = { ...preferences, notifications } as UserPreferences;
setUserPreferences(updatedPreferences);
setPreferences(updatedPreferences);
};

return (
<div>
<h1>User Preferences</h1>
<div>
<label>Theme:</label>
<select value={preferences?.theme} onChange={(e) => handleThemeChange(e.target.value)}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div>
<label>Notifications:</label>
<input
type="checkbox"
checked={preferences?.notifications}
onChange={(e) => handleNotificationsChange(e.target.checked)}
/>
</div>
</div>
);
};

export default UserPreferencesComponent;

5.2 Scenario 2: Shopping Cart​

import React, { useState, useEffect } from 'react';
import { setLocalStorageItem, getLocalStorageItem, removeLocalStorageItem } from './localStorageUtils';

interface CartItem {
id: number;
name: string;
price: number;
}

const ShoppingCartComponent: React.FC = () => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);

useEffect(() => {
const storedCartItems = getLocalStorageItem<CartItem[]>('cartItems');
if (storedCartItems) {
setCartItems(storedCartItems);
}
}, []);

const addToCart = (item: CartItem) => {
const updatedCartItems = [...cartItems, item];
setLocalStorageItem('cartItems', updatedCartItems);
setCartItems(updatedCartItems);
};

const removeFromCart = (id: number) => {
const updatedCartItems = cartItems.filter((item) => item.id !== id);
setLocalStorageItem('cartItems', updatedCartItems);
setCartItems(updatedCartItems);
};

return (
<div>
<h1>Shopping Cart</h1>
<ul>
{cartItems.map((item) => (
<li key={item.id}>
{item.name} - ${item.price}
<button onClick={() => removeFromCart(item.id)}>Remove</button>
</li>
))}
</ul>
<button onClick={() => addToCart({ id: Date.now(), name: 'New Item', price: 10 })}>Add Item</button>
</div>
);
};

export default ShoppingCartComponent;

6-Design Diagrams​

6.1 Component Diagram​

+-------------------+ +-------------------+ +-------------------+
| App | | UserPreferences | | ShoppingCart |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) User Preferences | |
|-------------------------->| |
| | (2) Shopping Cart |
| |-------------------------->|
| | |
| (3) Local Storage | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| App | | UserPreferences | | ShoppingCart |
+-------------------+ +-------------------+ +-------------------+

6.2 Sequence Diagram​

+-------------------+ +-------------------+ +-------------------+
| User | | UserPreferences | | Local Storage |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Change Theme | |
|-------------------------->| |
| | (2) Update Preferences |
| |-------------------------->|
| | |
| (3) Store Preferences | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| User | | UserPreferences | | Local Storage |
+-------------------+ +-------------------+ +-------------------+

7. Unit Test Cases​

7.1 UserPreferencesComponent.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import UserPreferencesComponent from '../../src/components/UserPreferencesComponent';
import { setUserPreferences, getUserPreferences } from '../../src/utils/localStorageUtils';

jest.mock('../../src/utils/localStorageUtils', () => ({
setUserPreferences: jest.fn(),
getUserPreferences: jest.fn(),
}));

test('UserPreferencesComponent updates and retrieves preferences', () => {
(getUserPreferences as jest.Mock).mockReturnValue({ theme: 'light', notifications: true });

const { getByLabelText, getByText } = render(<UserPreferencesComponent />);

fireEvent.change(getByLabelText('Theme:'), { target: { value: 'dark' } });
expect(setUserPreferences).toHaveBeenCalledWith({ theme: 'dark', notifications: true });

fireEvent.click(getByLabelText('Notifications:'));
expect(setUserPreferences).toHaveBeenCalledWith({ theme: 'dark', notifications: false });
});

7.2 ShoppingCartComponent.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import ShoppingCartComponent from '../../src/components/ShoppingCartComponent';
import { setLocalStorageItem, getLocalStorageItem, removeLocalStorageItem } from '../../src/utils/localStorageUtils';

jest.mock('../../src/utils/localStorageUtils', () => ({
setLocalStorageItem: jest.fn(),
getLocalStorageItem: jest.fn(),
removeLocalStorageItem: jest.fn(),
}));

test('ShoppingCartComponent adds and removes items', () => {
(getLocalStorageItem as jest.Mock).mockReturnValue([{ id: 1, name: 'Item 1', price: 10 }]);

const { getByText } = render(<ShoppingCartComponent />);

fireEvent.click(getByText('Add Item'));
expect(setLocalStorageItem).toHaveBeenCalled();

fireEvent.click(getByText('Remove'));
expect(removeLocalStorageItem).toHaveBeenCalled();
});

8. Commands to Init and Add Dependencies​

# Initialize a new React project with TypeScript
yarn create react-app my-app --template typescript

# Navigate to the project directory
cd my-app

# Add Testing Library
yarn add --dev @testing-library/react @testing-library/jest-dom

9. Conclusion​

Local storage is a powerful tool for persisting data in web applications. This article provided a deep dive into best practices for handling local storage in ReactJS with TypeScript, focusing on functional components and the latest version of the tech stack. We explored real production scenarios with TypeScript code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn.

By understanding and applying these best practices, developers can effectively manage local storage in their ReactJS applications, ensuring they remain scalable, maintainable, and performant.

10. More Samples​

10.1 Project Setup​

To get started, we need to set up a React project with TypeScript and add the necessary dependencies using Yarn.

Yarn Commands

# Create a React project with TypeScript template
yarn create react-app local-storage-app --template typescript

# Navigate into the project directory
cd local-storage-app

# Add any additional dependencies if needed (e.g., testing libraries)
yarn add @testing-library/react @testing-library/jest-dom

Project Folder Structure

local-storage-app/
├── src/
│ ├── components/
│ │ ├── LocalStorageHandler.tsx
│ │ └── UserPreferences.tsx
│ ├── hooks/
│ │ └── useLocalStorage.ts
│ ├── tests/
│ │ └── LocalStorageHandler.test.tsx
│ ├── App.tsx
│ └── index.tsx
├── public/
└── package.json

useLocalStorage.ts

// src/hooks/useLocalStorage.ts
import { useState } from 'react';

/**
* Custom hook for local storage handling
* @param key - The key under which data is stored in local storage
* @param initialValue - The initial value to use if no value is stored
* @returns A tuple containing the stored value and a function to set the value
*/
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? (JSON.parse(item) as T) : initialValue;
} catch (error) {
console.error('Error reading from local storage', error);
return initialValue;
}
});

/**
* Sets a new value in local storage
* @param value - The new value to store
*/
const setValue = (value: T) => {
try {
setStoredValue(value);
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error('Error saving to local storage', error);
}
};

return [storedValue, setValue] as const;
}

export default useLocalStorage;

UserPreferences: Detailed Code for Using useLocalStorage in a Component

// src/components/UserPreferences.tsx
import React from 'react';
import useLocalStorage from '../hooks/useLocalStorage';

const UserPreferences: React.FC = () => {
// Using the custom hook to manage theme preference
const [theme, setTheme] = useLocalStorage<string>('theme', 'light');

// Toggles between 'light' and 'dark' themes
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};

return (
<div>
<h1>User Preferences</h1>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>
Toggle Theme
</button>
</div>
);
};

export default UserPreferences;

Type-Safe Local Storage Utility Functions For larger applications, you might prefer having utility functions to handle local storage logic:

// src/utils/localStorageUtils.ts
export const getLocalStorageItem = <T>(key: string, defaultValue: T): T => {
try {
const storedItem = localStorage.getItem(key);
return storedItem ? (JSON.parse(storedItem) as T) : defaultValue;
} catch (error) {
console.error(`Error reading key "${key}" from local storage`, error);
return defaultValue;
}
};

export const setLocalStorageItem = <T>(key: string, value: T): void => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error setting key "${key}" in local storage`, error);
}
};

Detailed Unit Test Cases

// src/tests/useLocalStorage.test.tsx
import { renderHook, act } from '@testing-library/react';
import useLocalStorage from '../hooks/useLocalStorage';

describe('useLocalStorage hook', () => {
beforeEach(() => {
localStorage.clear();
});

it('should return initial value if no value is stored', () => {
const { result } = renderHook(() => useLocalStorage('testKey', 'initialValue'));
expect(result.current[0]).toBe('initialValue');
});

it('should save and retrieve a value', () => {
const { result } = renderHook(() => useLocalStorage('testKey', 'initialValue'));

act(() => {
result.current[1]('newValue');
});

expect(result.current[0]).toBe('newValue');
expect(localStorage.getItem('testKey')).toBe(JSON.stringify('newValue'));
});

it('should handle JSON parsing errors gracefully', () => {
localStorage.setItem('testKey', '{invalid JSON');
const { result } = renderHook(() => useLocalStorage('testKey', 'defaultValue'));
expect(result.current[0]).toBe('defaultValue');
});
});

Commands to Run Unit Tests

# Run unit tests with Yarn
yarn test

References​


This article provides a comprehensive guide to best practices for local storage handling in ReactJS with TypeScript, including detailed code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn. By understanding and applying these practices, developers can leverage the full potential of local storage in their ReactJS projects.