buster/web/.cursor/rules/context_rules.mdc

54 lines
1.6 KiB
Plaintext
Raw Normal View History

2025-02-08 10:45:48 +08:00
---
description: Rules for the context directory
globs: src/context/**/*
---
# Context Creation Pattern
When creating new contexts in this project, we use the `@fluentui/react-context-selector` library for optimized context consumption. Follow this pattern:
1. Create the context using `createContext`:
```typescript
const MyContext = createContext<ReturnType<typeof useMyHook>>({} as ReturnType<typeof useMyHook>);
```
2. Create a Provider component:
```typescript
export const MyContextProvider: React.FC<PropsWithChildren> = React.memo(({ children }) => {
return (
<MyContext.Provider value={useMyHook()}>
{children}
</MyContext.Provider>
);
});
MyContextProvider.displayName = 'MyContextProvider';
```
3. Create a selector hook for consuming the context:
```typescript
export const useMyContextSelector = <T,>(
selector: ContextSelector<ReturnType<typeof useMyHook>, T>
) => {
return useContextSelector(MyContext, selector);
};
```
## Key Points
- Always use TypeScript for proper type inference
- Wrap the Provider component with `React.memo()` for performance optimization
- Set a `displayName` for better debugging
- Export the selector hook for consuming components to use
- Use `PropsWithChildren` type for the Provider component
## Benefits
- The context selector pattern allows for partial context updates without full re-renders
- TypeScript integration ensures type safety throughout the context usage
- Memoization of the Provider component prevents unnecessary re-renders
## Example Usage
```typescript
// In a consumer component:
const someValue = useMyContextSelector(context => context.someValue);
```