跳到主要内容

2 篇博文 含有标签「redux」

查看所有标签

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.

Deep Dive into State Management in ReactJS

· 阅读需 12 分钟

Introduction​

State management is a critical aspect of building complex ReactJS applications. Proper state management ensures that your application remains scalable, maintainable, and performant. This article will deep dive into state management in ReactJS, focusing on functional components and the latest version of the tech stack. We will explore two main state management options: React Context API and Redux. Additionally, 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. State Management Basics​

1.1 What is State?​

State in ReactJS is an object that represents the dynamic data of a component. It determines how the component renders and behaves. State can be local to a single component or shared across multiple components.

State management refers to managing data that changes over time, ensuring that the user interface updates appropriately. Choosing the right state management solution is crucial for developing scalable and maintainable applications. We'll explore useState and useReducer for local state management and Redux and Zustand for global state management, with detailed TypeScript examples.

1.2 Local State vs Global State​

  • Local State: State that is confined to a single component. It is managed using the useState hook.
  • Global State: State that is shared across multiple components. It is managed using state management libraries like React Context API or Redux.

2. Setting Up the Project​

Initialize the React Project with TypeScript​

Run the following commands to create a new React project with TypeScript and install the necessary dependencies:

# Create a new React app with TypeScript
yarn create react-app react-state-management --template typescript

# Navigate to the project folder
cd react-state-management

# Install Redux and Zustand for state management
yarn add redux react-redux @reduxjs/toolkit zustand

# Install TypeScript types for React and Redux
yarn add -D @types/react-redux

3. State Management Options​

3.1 React Context API​

The React Context API provides a way to pass data through the component tree without having to pass props down manually at every level. It is ideal for small to medium-sized applications.

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

interface AuthContextType {
isAuthenticated: boolean;
login: () => void;
logout: () => void;
}

const AuthContext = createContext<AuthContextType>({
isAuthenticated: false,
login: () => {},
logout: () => {},
});

export const AuthProvider: React.FC = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);

const login = () => setIsAuthenticated(true);
const logout = () => setIsAuthenticated(false);

return (
<AuthContext.Provider value={{ isAuthenticated, login, logout }}>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => useContext(AuthContext);

4. Local State Management with useState and useReducer​

4.1 Using useState​

useState is simple to use and ideal for managing local state.

TypeScript Code Sample:

import React, { useState } from 'react';

const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);

const increment = (): void => {
setCount(prevCount => prevCount + 1);
};

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

export default Counter;

Best Practices:

  • Use useState for simple and straightforward state updates.
  • Type your state variables for better type safety.

4.2 Using useReducer​

useReducer is suitable for managing complex state logic.

TypeScript Code Sample:

import React, { useReducer } from 'react';

interface State {
count: number;
}

interface Action {
type: 'increment' | 'decrement';
}

const initialState: State = { count: 0 };

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

const Counter: React.FC = () => {
const [state, dispatch] = useReducer(reducer, initialState);

return (
<div>
<p>Current Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};

export default Counter;

Best Practices:

  • Use useReducer when state logic is complex or involves multiple sub-values.
  • Type both state and actions for enhanced type safety.

5. Global State Management with Redux​

Redux is a predictable state container for JavaScript apps. It is widely used for managing global state in large-scale applications.

5.1 Architecture of Redux​

Redux Architecture:

+------------+ +---------------+ +-------------+
| Action | --> | Reducer | --> | Store |
+------------+ +---------------+ +-------------+
^ |
| |
+------------------------------------------+

5.2 Redux state machine​

Here's a textual representation of a state machine diagram for a Redux state management flow:

+--------------------+ Action +----------------------+
| | (dispatch) | |
| React Component | -----------------> | Action |
| | | (type & payload) |
+--------------------+ +----------------------+
|
|
Dispatches action
|
v
+----------------+
| |
| Reducer |
| (pure function)|
+----------------+
|
Updates state |
based on action |
v
+----------------+
| |
| Store |
| (holds state) |
+----------------+
|
State subscription |
triggers re-render |
of component |
v
+--------------------+ Updated +----------------------+
| | State | |
| React Component | <----------------- | Store |
| | | |
+--------------------+ +----------------------+

Explanation:​

  • React Component: The UI component where user interactions or events trigger actions.
  • Action: An object describing what type of event occurred (e.g., { type: 'INCREMENT' }).
  • Reducer: A pure function that takes the current state and an action, then returns a new state.
  • Store: The central place where the state is kept, updated, and managed.
  • State Flow: Components subscribe to the store to get updates when the state changes, causing a re-render to reflect new data.

5.2 Redux Samples​

The Simple One

import { createStore } from 'redux';

interface State {
count: number;
}

interface Action {
type: string;
}

const initialState: State = { count: 0 };

const reducer = (state = initialState, action: Action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

const store = createStore(reducer);

export default store;

The Sample of Details actions.ts:

export const increment = () => ({ type: 'INCREMENT' } as const);
export const decrement = () => ({ type: 'DECREMENT' } as const);

export type ActionType = ReturnType<typeof increment | typeof decrement>;

reducers.ts:

import { ActionType } from './actions';

interface State {
count: number;
}

const initialState: State = { count: 0 };

export const counterReducer = (state: State = initialState, action: ActionType): State => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

store.ts:

import { createStore } from 'redux';
import { counterReducer } from './reducers';

const store = createStore(counterReducer);

export default store;

App.tsx:

import React from 'react';
import { Provider, useDispatch, useSelector } from 'react-redux';
import store from './state/redux/store';
import { increment, decrement } from './state/redux/actions';

interface RootState {
count: number;
}

const App: React.FC = () => {
const count = useSelector((state: RootState) => state.count);
const dispatch = useDispatch();

return (
<Provider store={store}>
<div>
<p>Current Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
</Provider>
);
};

export default App;

6. Alternative Global State Management with Zustand​

Zustand offers a simple and flexible state management solution without the boilerplate of Redux.

6.1 Architecture of Zustand​

Simple Architecture:

Component --> useStore --> State & Actions

6.2 TypeScript Code Example​

useStore.ts:

import create from 'zustand';

interface StoreState {
count: number;
increment: () => void;
decrement: () => void;
}

const useStore = create<StoreState>(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
decrement: () => set(state => ({ count: state.count - 1 }))
}));

export default useStore;

App.tsx:

import React from 'react';
import useStore from './state/zustand/useStore';

const App

: React.FC = () => {
const { count, increment, decrement } = useStore();

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

export default App;

More Scenarios​

7.1 Scenario 1: User Authentication​

React Context API​

import React from 'react';
import { AuthProvider, useAuth } from './AuthContext';

const LoginPage: React.FC = () => {
const { login } = useAuth();

return (
<div>
<h1>Login Page</h1>
<button onClick={login}>Login</button>
</div>
);
};

const Dashboard: React.FC = () => {
const { isAuthenticated, logout } = useAuth();

return (
<div>
<h1>Dashboard</h1>
{isAuthenticated ? (
<button onClick={logout}>Logout</button>
) : (
<p>Please login to access the dashboard.</p>
)}
</div>
);
};

const App: React.FC = () => (
<AuthProvider>
<LoginPage />
<Dashboard />
</AuthProvider>
);

export default App;

Redux​

import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store';

const LoginPage: React.FC = () => {
const dispatch = useDispatch();

const login = () => dispatch({ type: 'LOGIN' });

return (
<div>
<h1>Login Page</h1>
<button onClick={login}>Login</button>
</div>
);
};

const Dashboard: React.FC = () => {
const isAuthenticated = useSelector((state: any) => state.isAuthenticated);
const dispatch = useDispatch();

const logout = () => dispatch({ type: 'LOGOUT' });

return (
<div>
<h1>Dashboard</h1>
{isAuthenticated ? (
<button onClick={logout}>Logout</button>
) : (
<p>Please login to access the dashboard.</p>
)}
</div>
);
};

const App: React.FC = () => (
<Provider store={store}>
<LoginPage />
<Dashboard />
</Provider>
);

export default App;

7.2 Scenario 2: Shopping Cart​

React Context API​

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

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

interface CartContextType {
cartItems: CartItem[];
addToCart: (item: CartItem) => void;
removeFromCart: (id: number) => void;
}

const CartContext = createContext<CartContextType>({
cartItems: [],
addToCart: () => {},
removeFromCart: () => {},
});

export const CartProvider: React.FC = ({ children }) => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);

const addToCart = (item: CartItem) => setCartItems([...cartItems, item]);
const removeFromCart = (id: number) =>
setCartItems(cartItems.filter((item) => item.id !== id));

return (
<CartContext.Provider value={{ cartItems, addToCart, removeFromCart }}>
{children}
</CartContext.Provider>
);
};

export const useCart = () => useContext(CartContext);

Redux​

import { createStore } from 'redux';

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

interface State {
cartItems: CartItem[];
}

interface Action {
type: string;
payload?: any;
}

const initialState: State = { cartItems: [] };

const reducer = (state = initialState, action: Action) => {
switch (action.type) {
case 'ADD_TO_CART':
return { cartItems: [...state.cartItems, action.payload] };
case 'REMOVE_FROM_CART':
return {
cartItems: state.cartItems.filter((item) => item.id !== action.payload),
};
default:
return state;
}
};

const store = createStore(reducer);

export default store;

8. Some Diagrams​

+-------------------+ +-------------------+ +-------------------+
| App | | AuthProvider | | CartProvider |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Auth Context | |
|--------------------------->| |
| | (2) Cart Context |
| |-------------------------->|
| | |
| (3) LoginPage | |
|<------------ --------------| |
| | |
| (4) Dashboard | |
|<------------ --------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| App | | AuthProvider | | CartProvider |
+-------------------+ +-------------------+ +-------------------+
+-------------------+ +-------------------+ +-------------------+
| User | | LoginPage | | AuthProvider |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Click Login Button | |
|-------------------------->| |
| | (2) Dispatch Login Action |
| |-------------------------->|
| | |
| (3) Update Auth State | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| User | | LoginPage | | AuthProvider |
+-------------------+ +-------------------+ +-------------------+

Project Folder Structure​

project-root/
├── src/
│ ├── components/
│ │ ├── LoginPage.tsx
│ │ ├── Dashboard.tsx
│ ├── contexts/
│ │ ├── AuthContext.tsx
│ │ ├── CartContext.tsx
│ ├── redux/
│ │ ├── store.ts
│ ├── App.tsx
│ ├── index.tsx
├── tests/
│ ├── components/
│ │ ├── LoginPage.test.tsx
│ │ ├── Dashboard.test.tsx
│ ├── contexts/
│ │ ├── AuthContext.test.tsx
│ │ ├── CartContext.test.tsx
│ ├── redux/
│ │ ├── store.test.ts
├── package.json
├── tsconfig.json
├── yarn.lock

Unit Test Cases​

LoginPage.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { AuthProvider, useAuth } from '../../src/contexts/AuthContext';
import LoginPage from '../../src/components/LoginPage';

const TestComponent: React.FC = () => {
const { isAuthenticated } = useAuth();
return <div>{isAuthenticated ? 'Logged In' : 'Logged Out'}</div>;
};

test('LoginPage logs in user', () => {
const { getByText } = render(
<AuthProvider>
<LoginPage />
<TestComponent />
</AuthProvider>
);

fireEvent.click(getByText('Login'));
expect(getByText('Logged In')).toBeInTheDocument();
});

Dashboard.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { AuthProvider, useAuth } from '../../src/contexts/AuthContext';
import Dashboard from '../../src/components/Dashboard';

const TestComponent: React.FC = () => {
const { isAuthenticated } = useAuth();
return <div>{isAuthenticated ? 'Logged In' : 'Logged Out'}</div>;
};

test('Dashboard logs out user', () => {
const { getByText } = render(
<AuthProvider>
<Dashboard />
<TestComponent />
</AuthProvider>
);

fireEvent.click(getByText('Logout'));
expect(getByText('Logged Out')).toBeInTheDocument();
});

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 Redux and React-Redux
yarn add redux react-redux

# Add React Context API (no additional packages needed)

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

Conclusion​

State management is a crucial aspect of building scalable and maintainable ReactJS applications. This article provided a deep dive into state management in ReactJS, focusing on functional components and the latest version of the tech stack. We explored two main state management options: React Context API and Redux. Additionally, we provided 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 concepts, developers can effectively manage state in their ReactJS applications, ensuring they remain scalable, maintainable, and performant.

References​


This article provides a comprehensive guide to state management in ReactJS, 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 state management in their ReactJS projects.