https://github.com/zhangyu1818/create-context-factory
`createContextFactory` is a React Context utility that is TypeScript-friendly.
https://github.com/zhangyu1818/create-context-factory
Last synced: 2 months ago
JSON representation
`createContextFactory` is a React Context utility that is TypeScript-friendly.
- Host: GitHub
- URL: https://github.com/zhangyu1818/create-context-factory
- Owner: zhangyu1818
- Created: 2024-11-16T11:02:35.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-11-16T11:09:47.000Z (about 1 year ago)
- Last Synced: 2025-06-16T07:57:58.804Z (6 months ago)
- Language: TypeScript
- Homepage: https://jsr.io/@reactils/create-context-factory@1.0.0
- Size: 1000 Bytes
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Create Context Factory
`createContextFactory` is a React Context utility that is TypeScript-friendly. No need to declare Context types separately or write Providers - it helps you manage and share state more elegantly.
## Features
- 🚀 Type-safe: Full TypeScript support
- 🎯 Selective subscription: Only subscribe to the states you need, avoid code clutter
- 🔄 Auto-merging: Automatically handles state combinations from multiple hooks
- 📦 Zero dependencies: Only depends on React
- 🎨 Clean and elegant: Uses factory pattern, say goodbye to boilerplate Context code
## Installation
```shell
npx jsr add @reactils/create-context-factory
```
```shell
pnpm dlx jsr add @reactils/create-context-factory
```
## Usage
```tsx
import { createContextFactory } from '@reactils/createContextFactory';
import { useState } from 'react';
// Define your hooks
const useModalOpen = () => {
const [isOpen, setIsOpen] = useState(false);
// Logic code...
return [isOpen, setIsOpen] as const;
};
// Create shared Context
const [Provider, useSelector] = createContextFactory(() => ({
pending: useIsPending(),
showModal: useState(false), // Use useState directly
}));
// Use in components
function App() {
return (
);
}
// Component A only subscribes to pending state
function ComponentA() {
const [isPending, setPending] = useSelector(state => state.pending);
// ...
}
// Component B only subscribes to modal state
function ComponentB() {
const [isOpen, setIsOpen] = useSelector(state => state.showModal);
// ...
}
```
> [!IMPORTANT]
> Please note that this tool currently cannot prevent Context re-renders.
## License
MIT