Add comprehensive MDC files for various technologies and frameworks

Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including:
- AI/ML libraries (PyTorch, TensorFlow, scikit-learn)
- Backend frameworks (Django, FastAPI, Express, Spring Boot)
- Frontend frameworks (React, Vue, Angular)
- Cloud platforms (AWS, Azure, GCP)
- Development tools (Docker, Kubernetes, Terraform)
- State management libraries
- UI component libraries
- Web technologies and APIs

Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
+429
View File
@@ -0,0 +1,429 @@
---
description: This rule provides comprehensive guidance for using MobX effectively, covering best practices for code organization, performance, testing, and common pitfalls. It aims to ensure efficient and maintainable state management in React and other JavaScript applications using MobX.
globs: **/*.{js,jsx,ts,tsx}
---
# MobX Best Practices and Coding Standards
This document outlines the best practices for using MobX in your projects. Following these guidelines will help you write more maintainable, performant, and robust code.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
* **Feature-Based Organization:** Organize your code by feature rather than by file type (e.g., components, stores, utils). This promotes better modularity and easier navigation.
src/
├── features/
│ ├── user-profile/
│ │ ├── components/
│ │ │ ├── UserProfile.jsx
│ │ │ └── UserDetails.jsx
│ │ ├── stores/
│ │ │ ├── userStore.js
│ │ ├── api/
│ │ │ └── userApi.js
│ │ └── utils/
│ │ └── userUtils.js
│ ├── product-listing/
│ │ └── ...
├── app.js
└── ...
* **Dedicated `stores` Directory:** Place all your MobX stores in a dedicated `stores` directory to clearly separate state management logic from the rest of your application.
* **Shared Utilities:** Create a `utils` directory for reusable utility functions.
### 1.2 File Naming Conventions
* **Descriptive Names:** Use descriptive names for files and modules that clearly indicate their purpose.
* **Consistent Case:** Maintain a consistent naming convention (e.g., camelCase for JavaScript files, PascalCase for React components).
### 1.3 Module Organization
* **Single Responsibility Principle:** Each module should have a single, well-defined responsibility.
* **Clear Exports:** Clearly define the exports of each module (e.g., named exports for individual functions, default export for the main component or store).
* **Avoid Circular Dependencies:** Ensure that modules do not have circular dependencies to prevent runtime errors and improve code maintainability. Use dependency injection if necessary.
### 1.4 Component Architecture
* **Presentational and Container Components:** Separate presentational (UI-focused) components from container (data-fetching and logic-handling) components. Presentational components receive data via props, while container components connect to MobX stores and pass data down.
jsx
// Container component
import React from 'react';
import { observer } from 'mobx-react-lite';
import { useUserStore } from './stores/userStore';
import UserProfile from './UserProfile';
const UserProfileContainer = observer(() => {
const userStore = useUserStore();
return <UserProfile user={userStore.user} />; // Pass data as props
});
export default UserProfileContainer;
// Presentational component
import React from 'react';
const UserProfile = ({ user }) => {
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
};
export default UserProfile;
* **Functional Components with Hooks:** Use functional components with the `useObserver` hook (or `observer` from `mobx-react-lite`) for better performance and readability.
jsx
import React from 'react';
import { observer } from 'mobx-react-lite';
import { useUserStore } from './stores/userStore';
const UserProfile = observer(() => {
const userStore = useUserStore();
return (
<div>
<h1>{userStore.user.name}</h1>
<p>{userStore.user.email}</p>
</div>
);
});
export default UserProfile;
* **Component Composition:** Favor component composition over deep inheritance to create reusable and flexible components.
### 1.5 Code Splitting Strategies
* **Route-Based Splitting:** Split your application into chunks based on routes or pages. This allows users to download only the code they need for the current view.
* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. Use `React.lazy` and `Suspense` for lazy loading components.
* **Vendor Splitting:** Separate your vendor dependencies (e.g., libraries) into a separate chunk. This allows browsers to cache vendor code separately from your application code.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to MobX
* **Observable State:** Use `@observable` to define the state that MobX should track for changes. Ensure that only necessary data is made observable to optimize performance.
* **Computed Properties:** Use `@computed` to derive values from observable state. Computed properties are automatically updated when their dependencies change and are cached for performance.
javascript
import { makeObservable, observable, computed } from 'mobx';
class Cart {
items = [];
constructor() {
makeObservable(this, {
items: observable,
totalPrice: computed
});
}
get totalPrice() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
* **Actions:** Use `@action` to modify the state. Actions ensure that state changes are batched and tracked by MobX. All state modifications should happen within actions to maintain predictability.
javascript
import { makeObservable, observable, computed, action } from 'mobx';
class Cart {
items = [];
constructor() {
makeObservable(this, {
items: observable,
totalPrice: computed,
addItem: action
});
}
get totalPrice() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
addItem(item) {
this.items.push(item);
}
}
* **Reactions:** Use `reaction`, `autorun`, and `when` to react to state changes. Use `reaction` for side effects that depend on specific observable values, `autorun` for side effects that depend on any observable value, and `when` for one-time side effects.
### 2.2 Recommended Approaches for Common Tasks
* **Form Handling:** Use MobX to manage form state. Create observable properties for each form field and use actions to update them.
jsx
import React from 'react';
import { observer } from 'mobx-react-lite';
import { makeObservable, observable, action } from 'mobx';
class FormStore {
name = '';
email = '';
constructor() {
makeObservable(this, {
name: observable,
email: observable,
setName: action,
setEmail: action
});
}
setName(value) {
this.name = value;
}
setEmail(value) {
this.email = value;
}
}
const formStore = new FormStore();
const Form = observer(() => {
return (
<form>
<input type="text" value={formStore.name} onChange={e => formStore.setName(e.target.value)} />
<input type="email" value={formStore.email} onChange={e => formStore.setEmail(e.target.value)} />
</form>
);
});
export default Form;
* **Asynchronous Operations:** Use actions to handle asynchronous operations such as API calls. Use `async/await` syntax to simplify asynchronous code.
javascript
import { makeObservable, observable, action } from 'mobx';
class UserStore {
user = null;
loading = false;
constructor() {
makeObservable(this, {
user: observable,
loading: observable,
fetchUser: action
});
}
async fetchUser(id) {
this.loading = true;
try {
const response = await fetch(`/api/users/${id}`);
this.user = await response.json();
} finally {
this.loading = false;
}
}
}
### 2.3 Anti-patterns and Code Smells to Avoid
* **Mutating Observables Directly:** Avoid directly mutating observable values outside of actions. This can lead to unexpected behavior and make it difficult to track state changes. Always use actions to modify observable state.
* **Over-Observing:** Avoid making everything observable. Only observe the data that needs to be tracked for changes. Over-observing can lead to performance issues.
* **Complex Computed Properties:** Keep computed properties simple and focused. Avoid complex logic in computed properties, as this can make your code harder to understand and debug.
* **Using `autorun` Excessively:** Be careful when using `autorun`, as it can easily lead to performance issues if not used correctly. Prefer `reaction` when you need to react to specific observable values.
* **Forgetting to Dispose Reactions:** Always dispose of reactions when they are no longer needed to prevent memory leaks. Use the `dispose` function returned by `autorun` and `reaction`.
### 2.4 State Management Best Practices
* **Single Source of Truth:** Maintain a single source of truth for your application's state. Avoid duplicating state across multiple stores.
* **Normalized State:** Normalize your state to reduce redundancy and improve performance. Store data in a flat, relational structure.
* **Immutability (with MobX's Mutability):** While MobX embraces mutability for performance, try to treat your data as immutable as possible, especially when working with arrays and objects. Instead of directly modifying arrays, use methods like `concat`, `slice`, and `filter` to create new arrays.
* **Centralized State Management:** Use MobX to manage all your application's state in a centralized location. This makes it easier to reason about and debug your code.
### 2.5 Error Handling Patterns
* **Try-Catch Blocks:** Use `try-catch` blocks to handle errors in asynchronous operations and other code that might throw exceptions.
* **Error Stores:** Create dedicated error stores to manage application-wide errors. This allows you to display error messages to the user and log errors for debugging.
* **Global Error Handling:** Implement global error handling to catch unhandled exceptions and prevent your application from crashing. Use `window.onerror` or `React Error Boundaries`.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Use `mobx-react-lite`:** Use `mobx-react-lite` instead of `mobx-react` for smaller bundle size and improved performance. `mobx-react-lite` provides hooks-based integration with React.
* **`useMemo` and `useCallback`:** Use `useMemo` and `useCallback` to optimize rendering performance by memoizing expensive calculations and preventing unnecessary re-renders.
jsx
import React, { useMemo } from 'react';
import { observer } from 'mobx-react-lite';
const MyComponent = observer(() => {
const expensiveValue = useMemo(() => {
// Perform expensive calculation
return computeExpensiveValue();
}, []);
return <div>{expensiveValue}</div>;
});
export default MyComponent;
* **`shouldComponentUpdate` (Class Components):** If you are using class components, implement `shouldComponentUpdate` to prevent unnecessary re-renders. Compare the previous and current props and state to determine if a re-render is necessary. Consider using `PureComponent`.
* **Minimize Re-renders:** Minimize the number of re-renders by optimizing your component structure and using techniques like `useMemo` and `useCallback`.
### 3.2 Memory Management
* **Dispose Reactions:** Always dispose of reactions when they are no longer needed to prevent memory leaks. Use the `dispose` function returned by `autorun` and `reaction`.
* **Avoid Creating Unnecessary Objects:** Avoid creating unnecessary objects, especially in computed properties and reactions. This can lead to memory leaks and performance issues.
* **Garbage Collection:** Be aware of JavaScript's garbage collection mechanism and avoid creating circular references that can prevent garbage collection.
### 3.3 Rendering Optimization
* **Virtualization:** Use virtualization techniques to render large lists efficiently. Virtualization renders only the visible items in the list, which can significantly improve performance.
* **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of updates to the UI. This can improve performance by preventing excessive re-renders.
### 3.4 Bundle Size Optimization
* **Code Splitting:** Use code splitting to reduce the initial bundle size of your application. This allows users to download only the code they need for the current view.
* **Tree Shaking:** Use tree shaking to remove dead code from your bundle. Tree shaking is a technique that removes unused code from your bundle, which can significantly reduce its size.
* **Minification:** Use minification to reduce the size of your code. Minification removes whitespace and comments from your code, which can reduce its size.
### 3.5 Lazy Loading Strategies
* **Lazy Loading Components:** Use `React.lazy` and `Suspense` to lazy load components. This allows you to load components on demand, which can improve the initial load time of your application.
* **Lazy Loading Images:** Use lazy loading for images to improve the initial load time of your application. This can be done using the `loading` attribute on the `img` element or using a library like `react-lazyload`.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and escaping output. Use libraries like `DOMPurify` to sanitize HTML.
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using CSRF tokens. CSRF tokens are unique, secret values that are included in requests to prevent attackers from forging requests on behalf of users.
* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or an ORM (Object-Relational Mapper). Parameterized queries escape user input, which prevents attackers from injecting malicious SQL code.
### 4.2 Input Validation
* **Server-Side Validation:** Validate user input on the server-side to prevent malicious data from being stored in your database.
* **Client-Side Validation:** Validate user input on the client-side to provide immediate feedback to the user and improve the user experience. However, always validate on the server-side as well, since client-side validation can be bypassed.
* **Regular Expressions:** Use regular expressions to validate user input. Regular expressions are a powerful tool for validating data against specific patterns.
### 4.3 Authentication and Authorization Patterns
* **Authentication:** Use a secure authentication mechanism to verify the identity of users. Use libraries like `Passport.js` or `Auth0` to simplify the authentication process.
* **Authorization:** Implement authorization to control access to resources based on the user's role. Use role-based access control (RBAC) or attribute-based access control (ABAC) to manage access permissions.
* **JSON Web Tokens (JWT):** Use JWTs to securely transmit user information between the client and the server. JWTs are digitally signed, which makes them tamper-proof.
### 4.4 Data Protection Strategies
* **Encryption:** Encrypt sensitive data at rest and in transit. Use HTTPS to encrypt data in transit and libraries like `bcrypt` to encrypt passwords.
* **Data Masking:** Mask sensitive data to protect it from unauthorized access. Data masking replaces sensitive data with fictitious data, which allows developers to work with the data without exposing the actual sensitive information.
* **Data Anonymization:** Anonymize data to remove personally identifiable information (PII). Data anonymization is a technique that removes or modifies PII to prevent it from being linked to a specific individual.
### 4.5 Secure API Communication
* **HTTPS:** Always use HTTPS to encrypt communication between the client and the server. HTTPS uses TLS/SSL to encrypt data in transit, which prevents eavesdropping.
* **API Keys:** Use API keys to authenticate requests to your API. API keys are unique, secret values that are used to identify the client making the request.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API. Rate limiting limits the number of requests that a client can make within a given time period.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
* **Test Stores in Isolation:** Unit test MobX stores in isolation to verify that their state and actions behave as expected. Use mocking and stubbing to isolate the stores from external dependencies.
* **Test Computed Properties:** Test computed properties to ensure that they correctly derive values from observable state.
* **Test Actions:** Test actions to ensure that they correctly modify the state.
### 5.2 Integration Testing
* **Test Components with Stores:** Integration test components with MobX stores to verify that they interact correctly. Use a testing library like `React Testing Library` to render the components and simulate user interactions.
* **Test API Interactions:** Test API interactions to ensure that data is correctly fetched from and sent to the server. Use mocking to isolate the components from the actual API.
### 5.3 End-to-End Testing
* **Automated Browser Tests:** Use end-to-end testing frameworks like Cypress or Selenium to automate browser tests. End-to-end tests verify that the entire application works correctly from the user's perspective.
### 5.4 Test Organization
* **Separate Test Files:** Create separate test files for each module or component. This makes it easier to find and run the tests.
* **Descriptive Test Names:** Use descriptive names for your tests that clearly indicate what they are testing.
* **Test Suites:** Organize your tests into test suites based on functionality or module.
### 5.5 Mocking and Stubbing
* **Mock Dependencies:** Use mocking to replace external dependencies with mock objects. This allows you to isolate the code being tested and control its behavior.
* **Stub Functions:** Use stubbing to replace functions with predefined return values or behavior. This allows you to control the behavior of the code being tested without actually executing it.
* **Mock API Calls:** Mock API calls to avoid making real API requests during testing. This makes your tests faster and more reliable.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
* **Forgetting to Wrap Components with `observer`:** Forgetting to wrap React components with `observer` (or using `useObserver`) prevents them from reacting to changes in the MobX store.
* **Directly Modifying Observable Arrays/Objects:** Directly modifying observable arrays or objects (e.g., `myArray[0] = 'new value'`) won't trigger reactivity. Always use the methods provided by MobX (e.g., `myArray.splice(0, 1, 'new value')` or `myObject.set('key', 'value')`).
* **Not Using `useLocalObservable` in Components:** Using `useLocalObservable` is crucial for creating isolated, component-specific stores, preventing unintended state sharing.
### 6.2 Edge Cases to Be Aware Of
* **React Strict Mode:** Be aware that React Strict Mode can cause MobX to re-run reactions multiple times. This can be useful for debugging, but it can also lead to performance issues.
* **Large Datasets:** Be careful when working with large datasets in MobX. Consider using virtualization techniques to improve performance.
### 6.3 Version-Specific Issues
* **MobX 5 vs. MobX 6:** Be aware of the differences between MobX 5 and MobX 6. MobX 6 introduced several breaking changes, including the removal of implicit observability. Make sure your code is compatible with the version of MobX you are using.
* **React Compatibility:** Ensure that your version of `mobx-react` or `mobx-react-lite` is compatible with your version of React.
### 6.4 Compatibility Concerns
* **Browser Compatibility:** Ensure that your code is compatible with the browsers you are targeting. Use polyfills to support older browsers.
* **Node.js Compatibility:** Ensure that your code is compatible with the version of Node.js you are using. Use a tool like `nvm` to manage multiple Node.js versions.
### 6.5 Debugging Strategies
* **MobX DevTools:** Use the MobX DevTools to inspect your application's state and track changes. The MobX DevTools is a browser extension that allows you to visualize your MobX stores and track changes in real-time.
* **Logging:** Use logging to track the execution of your code and identify errors. Use a logging library like `debug` to simplify the logging process.
* **Breakpoints:** Use breakpoints to pause the execution of your code and inspect its state. Breakpoints are a powerful tool for debugging complex code.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **VS Code:** Use VS Code as your IDE. VS Code has excellent support for JavaScript, TypeScript, and React, and it has a wide range of extensions that can improve your development workflow.
* **ESLint:** Use ESLint to enforce coding standards and identify potential errors. ESLint is a linter that can be configured to enforce a wide range of coding standards.
* **Prettier:** Use Prettier to automatically format your code. Prettier is a code formatter that can be configured to automatically format your code according to a set of rules.
### 7.2 Build Configuration
* **Webpack:** Use Webpack to bundle your code. Webpack is a module bundler that can be used to bundle your code and its dependencies into a single file.
* **Babel:** Use Babel to transpile your code to older versions of JavaScript. Babel is a transpiler that can be used to convert your code to older versions of JavaScript, which allows it to run on older browsers.
* **TypeScript:** Use TypeScript to add static typing to your code. TypeScript is a superset of JavaScript that adds static typing to the language. This can help you catch errors early and improve the maintainability of your code.
### 7.3 Linting and Formatting
* **ESLint:** Use ESLint to enforce coding standards and identify potential errors. Configure ESLint to use the recommended rules for React and MobX.
* **Prettier:** Use Prettier to automatically format your code. Configure Prettier to use a consistent code style.
* **Husky:** Use Husky to run linters and formatters before committing code. This ensures that all code committed to the repository meets the required standards.
### 7.4 Deployment Best Practices
* **Continuous Integration/Continuous Deployment (CI/CD):** Implement a CI/CD pipeline to automate the deployment process. This ensures that your code is automatically tested and deployed whenever changes are made.
* **Caching:** Use caching to improve the performance of your application. Cache static assets like images and JavaScript files to reduce the load on your server.
* **Content Delivery Network (CDN):** Use a CDN to distribute your static assets across multiple servers. This improves the performance of your application by serving assets from the server closest to the user.
### 7.5 CI/CD Integration
* **GitHub Actions:** Use GitHub Actions to automate your CI/CD pipeline. GitHub Actions is a CI/CD service that is integrated with GitHub. Use Jenkins, CircleCI, or other CI/CD tools.
* **Automated Testing:** Automate your testing process to ensure that your code is thoroughly tested before it is deployed. Use a testing framework like Jest or Mocha to write automated tests.
* **Automated Deployment:** Automate your deployment process to ensure that your code is deployed quickly and reliably. Use a deployment tool like `Capistrano` or `Deployer` to automate the deployment process.
+196
View File
@@ -0,0 +1,196 @@
---
description: This rule provides comprehensive guidance on Redux best practices, covering code structure, performance optimization, testing strategies, and common pitfalls to ensure robust and maintainable Redux applications.
globs: **/*.{js,jsx,ts,tsx}
---
- **Introduction:** This document outlines best practices for developing applications with Redux, covering various aspects from code organization to performance optimization.
## 1. Code Organization and Structure:
- **Directory Structure:** Organize your Redux-related files in a clear and maintainable structure. A feature-based approach is recommended.
- Example:
src/
├── app/
│ ├── store.js # Redux store configuration
├── features/
│ ├── counter/ # Feature module (e.g., 'counter')
│ │ ├── counterSlice.js # Redux slice (reducers + actions)
│ │ ├── Counter.jsx # React component
│ │ ├── counterAPI.js # API interaction logic
│ │ └── counterSelectors.js # Selectors
│ ├── todos/
│ │ └── ...
├── components/ # Reusable UI components
├── utils/ # Utility functions
└── ...
- **File Naming Conventions:** Use consistent and descriptive names for your files.
- Example:
- `counterSlice.js` for Redux slice files
- `Counter.jsx` for React components
- `counterActions.js` or preferably included in slice
- `counterSelectors.js` for selectors
- **Module Organization:** Group related logic into modules. Each feature should have its own directory containing its Redux slice, components, and selectors.
- **Component Architecture:** Use a container/presentational component pattern to separate data fetching and state management logic from UI rendering.
- **Container Components:** Connect to the Redux store and pass data to presentational components.
- **Presentational Components:** Focus on UI rendering and receive data and callbacks as props.
- **Code Splitting Strategies:** Implement code splitting to reduce the initial bundle size and improve loading times.
- **Route-based splitting:** Load different parts of the application based on the current route.
- **Component-based splitting:** Lazy-load components that are not immediately needed.
- Use `React.lazy` and `<Suspense>` for component-based splitting.
## 2. Common Patterns and Anti-patterns:
- **Design Patterns:**
- **Flux Standard Actions (FSA):** A convention for structuring Redux actions with a `type` and an optional `payload` and `error` property.
- **Selectors:** Use selectors (e.g., with Reselect) to derive data from the Redux store efficiently.
- **Thunks/Sagas:** Manage asynchronous side effects using Redux Thunk or Redux Saga.
- **Recommended Approaches:**
- **Redux Toolkit:** Use Redux Toolkit to simplify Redux development and reduce boilerplate.
- **Immutability:** Treat state as immutable and use immutable data structures or techniques to update it.
- **Normalization:** Normalize your state to reduce data duplication and improve data consistency.
- **Anti-patterns and Code Smells:**
- **Mutating State Directly:** Never mutate state directly. Always create new copies of objects and arrays.
- **Putting too much logic in components:** Keep components focused on rendering. Move complex logic to reducers, selectors, or middleware.
- **Large Reducers:** Split large reducers into smaller, more manageable reducers using `combineReducers`.
- **Over-fetching Data:** Fetch only the data that is needed by the component. Use selectors to derive specific data subsets from the state.
- **State Management Best Practices:**
- **Single Source of Truth:** Keep all application state in the Redux store.
- **Predictable State Updates:** Ensure that state updates are predictable and deterministic.
- **Minimize Global State:** Only store data that is truly global in the Redux store. Local component state should be used for UI-specific data.
- **Error Handling Patterns:**
- **Action-based Error Handling:** Dispatch actions to indicate errors and update the state accordingly.
- **Middleware Error Handling:** Use middleware to catch errors and log them to a central error reporting service.
## 3. Performance Considerations:
- **Optimization Techniques:**
- **Memoization:** Use memoization to avoid unnecessary re-renders. Use `React.memo` for functional components and `shouldComponentUpdate` for class components.
- **Selectors:** Use selectors with memoization (e.g., Reselect) to avoid recomputing derived data when the input state hasn't changed.
- **Batch Updates:** Batch multiple state updates into a single update to reduce the number of re-renders.
- **Debouncing/Throttling:** Use debouncing or throttling to limit the frequency of updates.
- **Memory Management:**
- **Avoid Memory Leaks:** Clean up event listeners and timers when components unmount.
- **Optimize Data Structures:** Use efficient data structures to reduce memory usage.
- **Rendering Optimization:**
- **Virtualization:** Use virtualization for large lists to only render the visible items.
- **Code Splitting:** Reduce the initial bundle size by splitting the code into smaller chunks.
- **Bundle Size Optimization:**
- **Tree Shaking:** Remove unused code from the bundle using tree shaking.
- **Minification:** Minify the code to reduce the bundle size.
- **Compression:** Compress the bundle using Gzip or Brotli.
- **Lazy Loading Strategies:**
- **Route-based Lazy Loading:** Load different routes on demand.
- **Component-based Lazy Loading:** Load components on demand using `React.lazy`.
## 4. Security Best Practices:
- **Common Vulnerabilities:**
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and escaping outputs.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens.
- **Data Injection:** Prevent data injection attacks by validating and sanitizing inputs.
- **Input Validation:**
- **Client-Side Validation:** Validate inputs on the client-side to provide immediate feedback to the user.
- **Server-Side Validation:** Validate inputs on the server-side to ensure data integrity.
- **Authentication and Authorization Patterns:**
- **JWT (JSON Web Tokens):** Use JWTs for authentication and authorization.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application.
- **Data Protection Strategies:**
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data to protect it from unauthorized access.
- **Secure API Communication:**
- **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
- **API Rate Limiting:** Implement API rate limiting to prevent abuse.
## 5. Testing Approaches:
- **Unit Testing Strategies:**
- **Test Reducers:** Test reducers to ensure that they update the state correctly.
- **Test Actions:** Test actions to ensure that they dispatch the correct payloads.
- **Test Selectors:** Test selectors to ensure that they derive the correct data from the state.
- **Integration Testing:**
- **Test Components:** Test components to ensure that they render correctly and interact with the Redux store.
- **Test Middleware:** Test middleware to ensure that they handle side effects correctly.
- **End-to-end Testing:**
- **Test User Flows:** Test user flows to ensure that the application works as expected from the user's perspective.
- **Test Organization:**
- **Test Directory Structure:** Organize tests in a clear and maintainable structure.
- Example:
src/
├── features/
│ ├── counter/
│ │ ├── counterSlice.test.js
│ │ ├── Counter.test.jsx
- **Mocking and Stubbing:**
- **Mock API Calls:** Mock API calls to isolate components and reducers during testing.
- **Stub Dependencies:** Stub external dependencies to control their behavior during testing.
## 6. Common Pitfalls and Gotchas:
- **Frequent Mistakes:**
- **Forgetting to Return State:** Reducers must always return the new state. If no change, return the original state.
- **Incorrectly Updating Nested Objects:** Remember to create copies of all levels when updating nested objects.
- **Not Handling Asynchronous Actions Correctly:** Using thunks or sagas incorrectly can lead to unexpected behavior.
- **Edge Cases:**
- **Initial State:** Ensure that the initial state is correctly defined.
- **Handling Errors:** Handle errors gracefully and provide informative error messages.
- **Empty States:** Handle empty states correctly to avoid unexpected behavior.
- **Version-Specific Issues:**
- **React Redux v8 vs v7:** Be aware of the changes introduced in React Redux v8, such as the improved performance and the new `useSyncExternalStore` hook.
- **Compatibility Concerns:**
- **Browser Compatibility:** Ensure that the application works correctly in all supported browsers.
- **Device Compatibility:** Ensure that the application works correctly on all supported devices.
- **Debugging Strategies:**
- **Redux DevTools:** Use the Redux DevTools extension to inspect the state and track actions.
- **Console Logging:** Use console logging to debug code and track state changes.
- **Debugging Tools:** Use browser debugging tools to step through code and inspect variables.
## 7. Tooling and Environment:
- **Recommended Development Tools:**
- **Redux DevTools Extension:** Inspect Redux state and actions.
- **VS Code with Redux Extension:** Provides code completion, linting, and debugging support for Redux.
- **Build Configuration:**
- **Webpack/Parcel/Rollup:** Use a module bundler to bundle the code and optimize it for production.
- **Babel:** Use Babel to transpile the code to older versions of JavaScript.
- **Linting and Formatting:**
- **ESLint:** Use ESLint to enforce code style and prevent errors.
- **Prettier:** Use Prettier to automatically format the code.
- **Deployment Best Practices:**
- **Environment Variables:** Use environment variables to configure the application for different environments.
- **CDN:** Use a CDN to serve static assets.
- **CI/CD Integration:**
- **Automated Testing:** Run tests automatically as part of the CI/CD pipeline.
- **Automated Deployment:** Deploy the application automatically to different environments.
This comprehensive guide should help you build robust, maintainable, and performant Redux applications. Remember to stay up-to-date with the latest best practices and tools in the Redux ecosystem.
@@ -0,0 +1,672 @@
---
description: This rule provides guidelines for using Zustand, a simple and unopinionated state management library, in React applications. It covers best practices for code organization, performance optimization, testing, and common pitfalls to avoid.
globs: **/*.{js,jsx,ts,tsx}
---
# Zustand Best Practices
This document outlines best practices for using Zustand in your React applications. Zustand is a simple and unopinionated state management library. Following these guidelines will help you write maintainable, performant, and scalable applications.
## 1. Code Organization and Structure
### 1.1. Directory Structure
Organize your store files in a dedicated directory, such as `store` or `state`, at the root of your project or within a specific feature directory. This enhances discoverability and maintainability.
src/
├── components/
│ ├── ...
├── store/
│ ├── index.ts # Main store file (optional)
│ ├── bearStore.ts # Example store
│ ├── fishStore.ts # Example store
│ └── utils.ts # Utility functions for stores
├── App.tsx
└── ...
### 1.2. File Naming Conventions
Use descriptive names for your store files, typically reflecting the domain or feature the store manages. For example, `userStore.ts`, `cartStore.js`, or `settingsStore.tsx`. Use PascalCase for the store name itself (e.g., `UserStore`).
### 1.3. Module Organization
- **Single Store per File:** Prefer defining one Zustand store per file. This improves readability and maintainability.
- **Slices Pattern:** For complex stores, consider using the slices pattern to divide the store into smaller, more manageable pieces. Each slice manages a specific part of the state and its related actions.
typescript
// store/bearStore.ts
import { StateCreator, create } from 'zustand';
interface BearSlice {
bears: number;
addBear: () => void;
}
const createBearSlice: StateCreator<BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
});
export const useBearStore = create<BearSlice>()((...a) => ({
...createBearSlice(...a),
}));
// Another slice could be in fishStore.ts, etc.
### 1.4. Component Architecture
- **Presentational and Container Components:** Separate presentational (UI) components from container components that interact with the Zustand store. Container components fetch data from the store and pass it down to presentational components.
- **Hooks for Data Fetching:** Utilize Zustand's `useStore` hook within container components to subscribe to specific parts of the state.
### 1.5. Code Splitting Strategies
- **Lazy Loading Stores:** Load stores on demand using dynamic imports. This can reduce the initial bundle size, especially for larger applications.
- **Feature-Based Splitting:** Split your application into feature modules and create separate stores for each feature. This allows for independent loading and reduces dependencies between different parts of the application.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns Specific to Zustand
- **Colocated Actions and State:** Keep actions and the state they modify within the same store. This promotes encapsulation and makes it easier to understand how the store's state is updated.
- **Selectors:** Use selectors to derive computed values from the store's state. Selectors should be memoized to prevent unnecessary re-renders.
typescript
// store/userStore.ts
import { create } from 'zustand';
interface UserState {
name: string;
age: number;
}
interface UserActions {
setName: (name: string) => void;
isAdult: () => boolean; // Selector
}
export const useUserStore = create<UserState & UserActions>((set, get) => ({
name: 'John Doe',
age: 20,
setName: (name) => set({ name }),
isAdult: () => get().age >= 18, // Selector
}));
### 2.2. Recommended Approaches for Common Tasks
- **Asynchronous Actions:** Use `async/await` within actions to handle asynchronous operations such as fetching data from an API.
typescript
interface DataState {
data: any | null;
isLoading: boolean;
fetchData: () => Promise<void>;
}
export const useDataStore = create<DataState>((set) => ({
data: null,
isLoading: false,
fetchData: async () => {
set({ isLoading: true });
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
set({ data, isLoading: false });
} catch (error) {
console.error('Error fetching data:', error);
set({ isLoading: false, data: null });
}
},
}));
- **Persisting State:** Use the `zustand/middleware`'s `persist` middleware to persist the store's state to local storage or another storage mechanism. Configure a `partialize` function to select the state you want to persist.
typescript
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface AuthState {
token: string | null;
setToken: (token: string | null) => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
token: null,
setToken: (token) => set({ token }),
}),
{
name: 'auth-storage', // unique name
partialize: (state) => ({ token: state.token }), // Only persist the token
}
)
)
### 2.3. Anti-patterns and Code Smells to Avoid
- **Over-reliance on Global State:** Avoid storing everything in a single global store. Instead, break down your application's state into smaller, more manageable stores based on feature or domain.
- **Mutating State Directly:** Never mutate the state directly. Always use the `set` function provided by Zustand to ensure proper state updates and re-renders. Consider using Immer middleware (`zustand/middleware`) for immutable updates with mutable syntax.
- **Complex Selectors without Memoization:** Avoid complex selectors that perform expensive computations without memoization. This can lead to performance issues, especially with frequent state updates.
- **Creating Stores Inside Components:** Do not define Zustand stores inside React components. This will cause the store to be re-created on every render, leading to data loss and unexpected behavior.
### 2.4. State Management Best Practices
- **Single Source of Truth:** Treat the Zustand store as the single source of truth for your application's state.
- **Minimize State:** Store only the essential data in the store. Derive computed values using selectors.
- **Clear State Transitions:** Ensure that state transitions are predictable and well-defined. Avoid complex and convoluted update logic.
### 2.5. Error Handling Patterns
- **Try/Catch Blocks in Actions:** Wrap asynchronous actions in `try/catch` blocks to handle potential errors. Update the state to reflect the error status.
- **Error Boundary Components:** Use React error boundary components to catch errors that occur during rendering.
- **Centralized Error Logging:** Implement a centralized error logging mechanism to track errors that occur in your application. Send error reports to a monitoring service.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Selective Updates:** Use selectors to subscribe to only the specific parts of the state that your component needs. This prevents unnecessary re-renders when other parts of the state change.
- **Shallow Equality Checks:** By default, Zustand uses strict equality (`===`) for state comparisons. If you're using complex objects, use `shallow` from `zustand/shallow` as an equality function in `useStore` to avoid unnecessary re-renders.
- **Memoization:** Memoize selectors using libraries like `reselect` or `lodash.memoize` to prevent unnecessary re-computations.
- **Batch Updates:** Use `unstable_batchedUpdates` from `react-dom` to batch multiple state updates into a single render cycle.
### 3.2. Memory Management
- **Avoid Leaks:** Ensure that you are not creating memory leaks by properly cleaning up any subscriptions or event listeners that you create.
- **Limit Store Size:** Keep your stores as small as possible by only storing the data that you need.
### 3.3. Rendering Optimization
- **Virtualization:** If you are rendering large lists of data, use virtualization techniques (e.g., `react-window`, `react-virtualized`) to only render the visible items.
- **Code Splitting:** Split your application into smaller bundles to reduce the initial load time.
### 3.4. Bundle Size Optimization
- **Tree Shaking:** Ensure that your build process is configured to perform tree shaking, which removes unused code from your bundles.
- **Minimize Dependencies:** Use only the dependencies that you need. Avoid importing entire libraries when you only need a few functions.
- **Compression:** Compress your bundles using tools like Gzip or Brotli.
### 3.5. Lazy Loading Strategies
- **Component-Level Lazy Loading:** Lazy load components using `React.lazy` and `Suspense`.
- **Route-Based Lazy Loading:** Lazy load routes using `react-router-dom`'s `lazy` function.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and How to Prevent Them
- **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF):** Protect your API endpoints from CSRF attacks by implementing CSRF tokens.
- **Sensitive Data Exposure:** Avoid storing sensitive data in the store unless absolutely necessary. Encrypt sensitive data if it must be stored.
### 4.2. Input Validation
- **Server-Side Validation:** Always validate user inputs on the server-side.
- **Client-Side Validation:** Perform client-side validation to provide immediate feedback to the user.
### 4.3. Authentication and Authorization Patterns
- **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of your application based on user roles.
### 4.4. Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and other outputs.
### 4.5. Secure API Communication
- **HTTPS:** Use HTTPS to encrypt communication between the client and server.
- **API Rate Limiting:** Implement API rate limiting to prevent abuse.
## 5. Testing Approaches
### 5.1. Unit Testing Strategies
- **Test Store Logic:** Write unit tests to verify the logic of your Zustand stores.
- **Mock Dependencies:** Mock any external dependencies (e.g., API calls) to isolate the store logic.
- **Test State Transitions:** Ensure that state transitions are correct by asserting the expected state after each action.
### 5.2. Integration Testing
- **Test Component Interactions:** Write integration tests to verify that your components interact correctly with the Zustand store.
- **Render Components:** Render your components and simulate user interactions to test the integration between the UI and the store.
### 5.3. End-to-End Testing
- **Simulate User Flows:** Write end-to-end tests to simulate complete user flows through your application.
- **Test Real-World Scenarios:** Test real-world scenarios to ensure that your application is working correctly in a production-like environment.
### 5.4. Test Organization
- **Colocate Tests:** Colocate your tests with the code that they are testing.
- **Use Descriptive Names:** Use descriptive names for your test files and test cases.
### 5.5. Mocking and Stubbing
- **Jest Mocks:** Use Jest's mocking capabilities to mock external dependencies.
- **Sinon Stubs:** Use Sinon to create stubs for functions and methods.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes Developers Make
- **Incorrectly Using `set`:** Forgetting to use the functional form of `set` when updating state based on the previous state.
- **Not Handling Asynchronous Errors:** Failing to handle errors in asynchronous actions.
- **Over-relying on `shallow`:** Using `shallow` equality when a deep comparison is actually required.
### 6.2. Edge Cases to Be Aware Of
- **Race Conditions:** Be aware of potential race conditions when handling asynchronous actions.
- **Context Loss:** Ensure that the Zustand provider is properly configured to avoid context loss issues.
### 6.3. Version-Specific Issues
- **Check Release Notes:** Always check the release notes for new versions of Zustand to be aware of any breaking changes or new features.
### 6.4. Compatibility Concerns
- **React Version:** Ensure that your version of React is compatible with the version of Zustand that you are using.
### 6.5. Debugging Strategies
- **Zustand Devtools:** Use the Zustand Devtools extension to inspect the store's state and track state changes.
- **Console Logging:** Use console logging to debug your store logic and component interactions.
- **Breakpoints:** Set breakpoints in your code to step through the execution and inspect the state.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **VS Code:** Use VS Code as your code editor.
- **ESLint:** Use ESLint to enforce code style and prevent errors.
- **Prettier:** Use Prettier to automatically format your code.
- **Zustand Devtools:** Use the Zustand Devtools extension to inspect the store's state.
### 7.2. Build Configuration
- **Webpack:** Use Webpack to bundle your code.
- **Parcel:** Use Parcel for zero-configuration bundling.
- **Rollup:** Use Rollup for building libraries.
### 7.3. Linting and Formatting
- **ESLint:** Configure ESLint to enforce code style and best practices.
- **Prettier:** Configure Prettier to automatically format your code.
- **Husky:** Use Husky to run linters and formatters before committing code.
### 7.4. Deployment Best Practices
- **Environment Variables:** Use environment variables to configure your application for different environments.
- **CDN:** Use a CDN to serve your static assets.
- **Caching:** Implement caching to improve performance.
### 7.5. CI/CD Integration
- **GitHub Actions:** Use GitHub Actions to automate your build, test, and deployment processes.
- **CircleCI:** Use CircleCI to automate your build, test, and deployment processes.
- **Jenkins:** Use Jenkins to automate your build, test, and deployment processes.
## 8. Zustand-X (zustandx.udecode.dev)
Zustand-X builds on top of Zustand to reduce boilerplate and enhance features, providing a store factory with derived selectors and actions.
### 8.1. Key Features
- **Less Boilerplate:** Simplified store creation.
- **Modular State Management:** Derived selectors and actions.
- **Middleware Support:** Integrates with `immer`, `devtools`, and `persist`.
- **TypeScript Support:** Full TypeScript support.
- **React-Tracked Support:** Integration with `react-tracked`.
### 8.2. Usage
javascript
import { createStore } from 'zustand-x';
const repoStore = createStore('repo')({
name: 'zustandX',
stars: 0,
owner: {
name: 'someone',
email: 'someone@xxx.com',
},
});
// Hook store
repoStore.useStore;
// Vanilla store
repoStore.store;
// Selectors
repoStore.use.name();
repoStore.get.name();
// Actions
repoStore.set.name('new name');
// Extend selectors
repoStore.extendSelectors((state, get, api) => ({
validName: () => get.name().trim(),
title: (prefix) => `${prefix + get.validName()} with ${get.stars()} stars`,
}));
// Extend actions
repoStore.extendActions((set, get, api) => ({
validName: (name) => {
set.name(name.trim());
},
reset: (name) => {
set.validName(name);
set.stars(0);
},
}));
### 8.3. Global Store
Combine multiple stores into a global store for easier access.
javascript
import { mapValuesKey } from 'zustand-x';
export const rootStore = {
repo: repoStore,
// other stores
};
export const useStore = () => mapValuesKey('use', rootStore);
export const useTrackedStore = () => mapValuesKey('useTracked', rootStore);
export const store = mapValuesKey('get', rootStore);
export const actions = mapValuesKey('set', rootStore);
// Usage
useStore().repo.name();
actions.repo.stars(store.repo.stars + 1);
## 9. zustand-ards
A library of simple, opinionated utilities for Zustand to improve the developer experience.
### 9.1 Installation
bash
pnpm i zustand-ards
# or
npm i zustand-ards
### 9.2 Basic Usage
javascript
import { withZustandards } from 'zustand-ards';
const useWithZustandards = withZustandards(useStore);
const { bears, increaseBears } = useWithZustandards(['bears', 'increaseBears']);
### 9.3 Store Hook Enhancements
- **`withZustandards`:** Combines `withArraySelector` and `withDefaultShallow`.
- **`withArraySelector`:** Adds an array selector to the store hook, eliminating the need for multiple hooks or complex selector functions.
- **`withDefaultShallow`:** Makes the store hook shallow by default, equivalent to passing `shallow` from `zustand/shallow` to the original hook.
javascript
import { withArraySelector } from 'zustand-ards';
const useStoreWithArray = withArraySelector(useExampleStore);
const { bears, increaseBears } = useStoreWithArray(['bears', 'increaseBears']);
import { withDefaultShallow } from 'zustand-ards';
const useShallowStore = withDefaultShallow(useExampleStore);
const { wizards } = useShallowStore((state) => ({ wizards: state.wizards }));
## 10. TypeScript Guide
### 10.1. Basic Usage
Annotate the store's state type using `create<T>()(...)`.
typescript
import { create } from 'zustand';
interface BearState {
bears: number;
increase: (by: number) => void;
}
const useBearStore = create<BearState>()((set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by }))
}));
### 10.2. Using `combine`
`combine` infers the state, so no need to type it.
typescript
import { create } from 'zustand';
import { combine } from 'zustand/middleware';
const useBearStore = create(
combine({ bears: 0 }, (set) => ({
increase: (by: number) => set((state) => ({ bears: state.bears + by }))
}))
);
### 10.3. Using Middlewares
Use middlewares immediately inside `create` to ensure contextual inference works correctly. Devtools should be used last to prevent other middlewares from mutating the `setState` before it.
typescript
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
interface BearState {
bears: number;
increase: (by: number) => void;
}
const useBearStore = create<BearState>()(
devtools(
persist(
(set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by }))
}),
{ name: 'bearStore' }
)
)
);
### 10.4. Authoring Middlewares and Advanced Usage
Zustand middlewares can mutate the store. Higher-kinded mutators are available for complex type problems.
### 10.5. Middleware Examples
**Middleware that doesn't change the store type:**
typescript
import { create, State, StateCreator, StoreMutatorIdentifier } from 'zustand';
type Logger = <
T extends State,
Mps extends [StoreMutatorIdentifier, unknown][] = [],
Mcs extends [StoreMutatorIdentifier, unknown][] = [],
>(f: StateCreator<T, Mps, Mcs>, name?: string) => StateCreator<T, Mps, Mcs>;
const loggerImpl = (f, name) => (set, get, store) => {
const loggedSet = (...a) => {
set(...a);
console.log(...(name ? [`${name}:`] : []), get());
};
const setState = store.setState;
store.setState = (...a) => {
setState(...a);
console.log(...(name ? [`${name}:`] : []), store.getState());
};
return f(loggedSet, get, store);
};
export const logger = loggerImpl;
**Middleware that changes the store type:** Requires advanced TypeScript features.
### 10.6. Slices Pattern
The slices pattern is a way to split a store into smaller, more manageable parts.
typescript
import { create, StateCreator } from 'zustand';
interface BearSlice {
bears: number;
addBear: () => void;
eatFish: () => void;
}
interface FishSlice {
fishes: number;
addFish: () => void;
}
const createBearSlice: StateCreator<BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
eatFish: () => set((state) => ({fishes: state.fishes -1}))
});
const createFishSlice: StateCreator<FishSlice> = (set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 }))
});
export const useBoundStore = create<BearSlice & FishSlice>()((...a) => ({
...createBearSlice(...a),
...createFishSlice(...a),
}));
### 10.7. Bounded useStore Hook for Vanilla Stores
Provides type safety when using `useStore` with vanilla stores.
## 11. Zustand Tools (zustand-tools)
Tools for simpler Zustand usage with React.
### 11.1. `createSimple(initStore, middlewares)`
Creates a simple store with correct typings and hooks for easier usage.
javascript
import { createSimple } from 'zustand-tools';
const demoStore = createSimple({ foo: 'bar' });
/*
* will provide:
* demoStore.useStore.getState().foo
* demoStore.useStore.getState().setFoo(value)
* demoStore.hooks.useFoo() => [value, setter] // like useState
*/
const useFoo = demoStore.hooks.useFoo;
function App() {
const [foo, setFoo] = useFoo();
useEffect(() => {
setFoo('newBar');
}, [setFoo]);
return <div>{foo}</div>;
}
### 11.2. `createSimpleContext(initStore, middlewares)`
Basically the same as `createSimple` but returns a provider to use the store only for a specific context.
### 11.3. `useAllData()`
Returns all data from the store using a shallow compare.
### 11.4. Adding Additional Actions
Add additional actions to the generated store.
javascript
import { createSimple } from 'zustand-tools';
const { useStore } = createSimple(
{ foo: 1 },
{
actions: (set) => ({
increaseFoo: (amount) => set((state) => ({ foo: state.foo + amount }))
})
}
);
useStore.getState().increaseFoo(5);
### 11.5. Adding Middlewares
Middlewares can be added by passing an array as middlewares in the second parameter.
javascript
import { createSimple } from 'zustand-tools';
import { devtools } from 'zustand/middleware';
const demoStore = createSimple({ foo: 'bar' }, { middlewares: [(initializer) => devtools(initializer, { enabled: true })] });
## 12. Practice with no Store Actions
### 12.1. Colocated Actions and State
The recommended usage is to colocate actions and states within the store.
javascript
export const useBoundStore = create((set) => ({
count: 0,
text: 'hello',
inc: () => set((state) => ({ count: state.count + 1 })),
setText: (text) => set({ text }),
}));
### 12.2. External Actions
An alternative approach is to define actions at the module level, external to the store.
javascript
export const useBoundStore = create(() => ({
count: 0,
text: 'hello',
}));
export const inc = () =>
useBoundStore.setState((state) => ({ count: state.count + 1 }));
export const setText = (text) => useBoundStore.setState({ text });
## Conclusion
By following these best practices, you can build robust and scalable applications using Zustand. Remember to adapt these guidelines to your specific project needs and coding style.