├── .changeset ├── README.md └── config.json ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── config.yml │ └── feature_request.yml ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── publish-commit.yaml │ ├── publish.yaml │ └── pull-request.yaml ├── .gitignore ├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── SECURITY.MD ├── package.json ├── packages └── with-react │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── src │ ├── index.test.tsx │ └── index.tsx │ ├── tsconfig.json │ ├── tsdown.config.ts │ └── vitest.config.ts ├── pnpm-lock.yaml └── pnpm-workspace.yaml /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@3.0.2/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": true, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: 🐞 Bug Report 2 | description: Create a bug report to help us improve 3 | title: "bug: " 4 | labels: ["🐞 unconfirmed bug"] 5 | body: 6 | - type: textarea 7 | attributes: 8 | label: Provide environment information 9 | description: | 10 | Run this command in your project root and paste the results: 11 | ```bash 12 | npx envinfo --system --binaries 13 | ``` 14 | 15 | validations: 16 | required: true 17 | - type: textarea 18 | attributes: 19 | label: Describe the bug 20 | description: A clear and concise description of the bug, as well as what you expected to happen when encountering it. 21 | validations: 22 | required: true 23 | - type: input 24 | attributes: 25 | label: Reproduction repo 26 | description: If applicable, please provide a link to a reproduction repo or a Stackblitz / CodeSandbox project. Your issue may be closed if this is not provided and we are unable to reproduce the issue. 27 | - type: textarea 28 | attributes: 29 | label: Expected behavior 30 | description: A clear and concise description of what you expected to happen. 31 | validations: 32 | required: true 33 | - type: textarea 34 | attributes: 35 | label: Actual behavior 36 | description: A clear and concise description of what actually happened. 37 | validations: 38 | required: true 39 | - type: textarea 40 | attributes: 41 | label: Steps to reproduce 42 | description: Steps to reproduce the behavior. 43 | placeholder: | 44 | 1. Go to '...' 45 | 2. Click on '....' 46 | 3. Scroll down to '....' 47 | 4. See error 48 | validations: 49 | required: true 50 | - type: textarea 51 | attributes: 52 | label: Screenshots 53 | description: If applicable, add screenshots to help explain your problem. 54 | - type: textarea 55 | attributes: 56 | label: Additional context 57 | description: Add any other context about the problem here. 58 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Ask a Question 4 | url: https://discord.gg/uZ39dxhj 5 | about: Ask questions and discuss with other community members 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: Suggest an idea for this project 3 | title: "feat: " 4 | labels: ["🌟 enhancement"] 5 | body: 6 | - type: textarea 7 | attributes: 8 | label: Is your feature request related to a problem? Please describe. 9 | description: A clear and concise description of what the problem is. 10 | validations: 11 | required: true 12 | - type: textarea 13 | attributes: 14 | label: Describe the solution you'd like to see 15 | description: A clear and concise description of what you want to happen. 16 | validations: 17 | required: true 18 | - type: textarea 19 | attributes: 20 | label: Describe alternate solutions 21 | description: A clear and concise description of any alternative solutions or features you've considered. 22 | validations: 23 | required: true 24 | - type: textarea 25 | attributes: 26 | label: Additional information 27 | description: Add any other information related to the feature here. If your feature request is related to any issues or discussions, link them here. 28 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Fixes # 2 | 3 | # Description 4 | 5 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. 6 | List any dependencies that are required for this change. 7 | 8 | ## Type of change 9 | 10 | Please mark relevant options with an `x` in the brackets. 11 | 12 | - [ ] Bug fix (non-breaking change which fixes an issue) 13 | - [ ] New feature (non-breaking change which adds functionality) 14 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 15 | - [ ] This change requires a documentation update 16 | - [ ] Algorithm update - updates algorithm documentation/questions/answers etc. 17 | - [ ] Other (please describe): 18 | 19 | # How Has This Been Tested? 20 | 21 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also 22 | list any relevant details for your test configuration 23 | 24 | - [ ] Integration tests 25 | - [ ] Unit tests 26 | - [ ] Manual tests 27 | - [ ] No tests required 28 | 29 | # Reviewer checklist 30 | 31 | Mark everything that needs to be checked before merging the PR. 32 | 33 | - [ ] Check if the UI is working as expected and is satisfactory 34 | - [ ] Check if the code is well documented 35 | - [ ] Check if the behavior is what is expected 36 | - [ ] Check if the code is well tested 37 | - [ ] Check if the code is readable and well formatted 38 | - [ ] Additional checks (document below if any) 39 | 40 | # Screenshots (if appropriate): 41 | 42 | # Questions (if appropriate): 43 | -------------------------------------------------------------------------------- /.github/workflows/publish-commit.yaml: -------------------------------------------------------------------------------- 1 | name: 🚀 pkg-pr-new 2 | on: [push, pull_request] 3 | 4 | concurrency: 5 | group: ${{ github.repository }}-${{ github.workflow }}-${{ github.ref }} 6 | cancel-in-progress: true 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v2 14 | 15 | - name: Install pnpm 16 | uses: pnpm/action-setup@v4 17 | 18 | - run: corepack enable 19 | - uses: actions/setup-node@v4 20 | with: 21 | node-version-file: "package.json" 22 | 23 | - name: Install dependencies 24 | run: pnpm install 25 | 26 | - name: Build 27 | run: pnpm run build 28 | 29 | - run: npx pkg-pr-new publish ./packages/* 30 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release: 10 | name: Release 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: write 14 | pull-requests: write 15 | actions: write 16 | id-token: write 17 | steps: 18 | - name: Checkout Repo 19 | uses: actions/checkout@v3 20 | 21 | - name: Install pnpm 22 | uses: pnpm/action-setup@v4 23 | 24 | - name: Setup Node.js 25 | uses: actions/setup-node@v3 26 | with: 27 | node-version-file: "package.json" 28 | 29 | - name: Install Dependencies 30 | run: pnpm install 31 | 32 | # - name: 🔐 Setup npm auth 33 | # run: | 34 | # echo "registry=https://registry.npmjs.org" >> ~/.npmrc 35 | # echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" >> ~/.npmrc 36 | 37 | - name: Create Release Pull Request or Publish to npm 38 | id: changesets 39 | uses: changesets/action@v1 40 | env: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 43 | with: 44 | title: "🚀 Release PR" 45 | commit: "chore: release" 46 | version: pnpm run version 47 | publish: pnpm run release 48 | -------------------------------------------------------------------------------- /.github/workflows/pull-request.yaml: -------------------------------------------------------------------------------- 1 | name: 🚀 PR 2 | 3 | concurrency: 4 | group: ${{ github.repository }}-${{ github.workflow }}-${{ github.ref }} 5 | cancel-in-progress: true 6 | 7 | on: [pull_request] # Run only on pull_request, to also get status updates in PRs. We omit push because this would run the steps two times (for push and pull_request). 8 | 9 | permissions: 10 | actions: write 11 | contents: read 12 | # Required to put a comment into the pull-request 13 | pull-requests: write 14 | 15 | jobs: 16 | lint: 17 | name: ⬣ Linting 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v4 21 | - uses: biomejs/setup-biome@v2 22 | - run: biome ci . --reporter=github 23 | 24 | typecheck: 25 | name: 🔎 Type check 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: 🛑 Cancel Previous Runs 29 | uses: styfle/cancel-workflow-action@0.12.1 30 | 31 | - name: ⬇️ Checkout repo 32 | uses: actions/checkout@v4 33 | - name: Install pnpm 34 | uses: pnpm/action-setup@v4 35 | - name: ⎔ Setup node 36 | uses: actions/setup-node@v4 37 | with: 38 | node-version-file: "package.json" 39 | 40 | - name: 📥 Download deps 41 | run: pnpm install 42 | 43 | - name: 🔎 Type check 44 | run: pnpm run typecheck 45 | 46 | vitest: 47 | name: ⚡ Unit Tests 48 | runs-on: ubuntu-latest 49 | steps: 50 | - name: 🛑 Cancel Previous Runs 51 | uses: styfle/cancel-workflow-action@0.12.1 52 | 53 | - name: ⬇️ Checkout repo 54 | uses: actions/checkout@v4 55 | 56 | - name: Install pnpm 57 | uses: pnpm/action-setup@v4 58 | 59 | - name: ⎔ Setup node 60 | uses: actions/setup-node@v4 61 | with: 62 | node-version-file: "package.json" 63 | 64 | - name: 📥 Download deps 65 | run: pnpm install 66 | 67 | - name: ⚡ Run vitest 68 | run: pnpm run test:cov 69 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | /dist 132 | .history 133 | .react-router -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.defaultFormatter": "esbenp.prettier-vscode", 3 | "editor.formatOnSave": true, 4 | "javascript.format.enable": false, 5 | "javascript.suggest.autoImports": true, 6 | "javascript.suggest.paths": true, 7 | "typescript.format.enable": false, 8 | "typescript.suggest.paths": true, 9 | "typescript.suggest.autoImports": true, 10 | "editor.renderWhitespace": "all", 11 | "editor.rulers": [120, 160], 12 | "editor.codeActionsOnSave": { 13 | "source.fixAll": "always", 14 | "source.organizeImports": "never", 15 | "source.organizeImports.biome": "always", 16 | "quickfix.biome": "always" 17 | }, 18 | "editor.insertSpaces": false, 19 | "editor.detectIndentation": true, 20 | "editor.trimAutoWhitespace": true, 21 | "files.trimTrailingWhitespace": true, 22 | "files.trimTrailingWhitespaceInRegexAndStrings": true, 23 | "files.trimFinalNewlines": true, 24 | "explorer.fileNesting.patterns": { 25 | "*.ts": "${basename}.*.${extname}", 26 | ".env": ".env.*", 27 | "*.tsx": "${basename}.*.${extname},${basename}.*.ts", 28 | "package.json": "*.json, *.yml, *.config.js, *.config.ts, *.yaml" 29 | }, 30 | "eslint.enable": false, 31 | "eslint.format.enable": false, 32 | } 33 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Forge 42 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # with-react 2 | 3 | ![GitHub Repo stars](https://img.shields.io/github/stars/jacobparis/with-react?style=social) 4 | ![npm](https://img.shields.io/npm/v/with-react?style=plastic) 5 | ![GitHub](https://img.shields.io/github/license/jacobparis/with-react?style=plastic) 6 | ![npm](https://img.shields.io/npm/dy/with-react?style=plastic) 7 | ![npm](https://img.shields.io/npm/dw/with-react?style=plastic) 8 | ![GitHub top language](https://img.shields.io/github/languages/top/jacobparis/with-react?style=plastic) 9 | 10 | A collection of React components that wrap React hooks to provide a more composable API. Each component accepts a render prop that receives the hook's return value. 11 | 12 | This enables a lot of features that previously violate the Rules of Hooks 13 | 14 | ## Conditional Hooks 15 | 16 | ```tsx 17 | function UserProfile({ user, showDetails }) { 18 | return ( 19 |
20 |

{user.name}

21 | 22 |

23 | This is a really long description and there could be more markup 24 | or other components between here and the top of the component. 25 | Since hooks need to be declared at the top of the component function, 26 | instead of in the JSX, you may want to use WithState instead of useState 27 | just for colocation reasons. 28 |

29 | 30 | {showDetails && ( 31 | 32 | {(lastLogin, setLastLogin) => ( 33 |
34 | Last login: {lastLogin} 35 | 38 |
39 | )} 40 |
41 | )} 42 |
43 | ) 44 | } 45 | ``` 46 | 47 | 48 | ## Hooks within loops 49 | 50 | This is a special case of conditional hooks, but sometimes you're rendering a lot of items in a loop and it's not worth creating a custom component for them because they require too much data from the parent scope. 51 | 52 | But then when you need to add some state to each one, React forces you to wrap it in a component. By using WithState, that component is provided for you and you can keep your list items owned by the parent. 53 | 54 | ```tsx 55 | const items = ['apple', 'banana', 'orange'] 56 | 57 | function FruitList() { 58 | return ( 59 | 71 | ) 72 | } 73 | ``` 74 | 75 | ## Form Status 76 | 77 | The `useFormStatus()` hook from react-dom treats any parent `
` like a context provider, and for that reason must be used in a child component of the form. 78 | 79 | Avoid creating a component boundary by using `WithFormStatus` and getting the value inline. 80 | 81 | ```tsx 82 | function SearchForm() { 83 | return ( 84 | 85 | 86 | 87 | {(status) => ( 88 | 91 | )} 92 | 93 |
94 | ) 95 | } 96 | ``` 97 | 98 | ## Promise Resolution 99 | 100 | The `use()` hook can unwrap promises, but it must be used in a child of the suspense boundary it's meant to trigger. Since data is best fetched at the route level, these promises will almost always be naturally higher than the UI wheir their suspense boundary needs to be. 101 | 102 | The WithUse component allows you to pass a promise and get its resolved value directly within it. 103 | 104 | This use-case resembles [React Router's Await component](https://reactrouter.com/api/components/Await), which is a better name but I had to stick with the theme here. 105 | 106 | ```tsx 107 | function UserDetails() { 108 | return ( 109 |
110 |

User Details

111 | }> 112 | 113 | {(user) => ( 114 |
115 |

Name: {user.name}

116 |

Email: {user.email}

117 |
118 | )} 119 |
120 |
121 |
122 | ) 123 | } 124 | ``` 125 | 126 | ## Available Components 127 | 128 | WithState and WithFormStatus are the most useful 129 | | Hook | Component | 130 | |------|-----------| 131 | | `useActionState` | `WithActionState` | 132 | | `useCallback` | `WithCallback` | 133 | | `useContext` | X | 134 | | `useDeferredValue` | `WithDeferredValue` | 135 | | `useEffect` | X | 136 | | `useFormStatus` | `WithFormStatus` | 137 | | `useId` | `WithId` | 138 | | `useImperativeHandle` | X | 139 | | `useInsertionEffect` | X | 140 | | `useLayoutEffect` | X | 141 | | `useMemo` | `WithMemo` | 142 | | `useReducer` | `WithReducer` | 143 | | `useRef` | X | 144 | | `useState` | `WithState` | 145 | | `useSyncExternalStore` | `WithSyncExternalStore` | 146 | | `useTransition` | `WithTransition` | 147 | | `use` | `WithUse` | 148 | -------------------------------------------------------------------------------- /SECURITY.MD: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ------- | ------------------ | 7 | | 1.0.x | :white_check_mark: | 8 | 9 | ## Reporting a Vulnerability 10 | 11 | In case of a vulnerability please reach out to active maintainers of the project and report it to them. -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-react", 3 | "version": "1.0.0", 4 | "description": "Composable component versions of React hooks", 5 | "scripts": { 6 | "build": "pnpm run --filter=\"./packages/**/*\" build", 7 | "build:watch": "pnpm build && pnpm run --filter=\"./packages/**/*\" --parallel build --watch", 8 | "clean": "git clean -fdX .", 9 | "clean:build": "git clean -fdx -e node_modules .", 10 | "typecheck": "pnpm run --filter=\"./packages/**/*\" --parallel typecheck", 11 | "test": "pnpm run --filter=\"./packages/**/*\" --parallel test", 12 | "test:cov": "pnpm run --filter=\"./packages/**/*\" --parallel test:cov", 13 | "dev": "pnpm build && pnpm run --parallel dev", 14 | "changeset": "changeset", 15 | "release": "changeset publish", 16 | "local-release": "changeset version && changeset publish", 17 | "version": "changeset version" 18 | }, 19 | "author": "jacobparis", 20 | "license": "MIT", 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/jacobparis/with-react.git" 24 | }, 25 | "bugs": { 26 | "url": "https://github.com/jacobparis/with-react/issues" 27 | }, 28 | "homepage": "https://github.com/jacobparis/with-react#readme", 29 | "peerDependencies": { 30 | "react": "^19.0.0", 31 | "react-dom": "^19.0.0" 32 | }, 33 | "devDependencies": { 34 | "@changesets/cli": "^2.29.0", 35 | "@testing-library/dom": "^10.4.0", 36 | "@testing-library/jest-dom": "^6.6.3", 37 | "@testing-library/react": "^16.3.0", 38 | "@testing-library/user-event": "^14.6.1", 39 | "@types/node": "^20.17.30", 40 | "@types/react": "^19.1.4", 41 | "@types/react-dom": "^19.1.5", 42 | "@vitest/ui": "^3.1.3", 43 | "jsdom": "^26.1.0", 44 | "lefthook": "^1.11.10", 45 | "prettier": "^3.5.3", 46 | "react": "^19.1.0", 47 | "react-dom": "^19.1.0", 48 | "vitest": "^3.1.3" 49 | }, 50 | "packageManager": "pnpm@10.11.0", 51 | "engines": { 52 | "pnpm": ">=10.6.5", 53 | "node": ">=20.0.0" 54 | }, 55 | "prettier": { 56 | "trailingComma": "all", 57 | "printWidth": 120, 58 | "semi": false, 59 | "useTabs": true 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /packages/with-react/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jacobparis/with-react/25a74926d579f3bfa815f14ee836466ebb40fc08/packages/with-react/README.md -------------------------------------------------------------------------------- /packages/with-react/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-react", 3 | "version": "1.0..0", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "with-react", 9 | "version": "1.1.2", 10 | "license": "MIT", 11 | "dependencies": { 12 | "react": "^19.1.0" 13 | }, 14 | "devDependencies": { 15 | "@arethetypeswrong/cli": "^0.17.4", 16 | "@changesets/cli": "^2.29.0", 17 | "@types/node": "^20.17.30", 18 | "@vitest/coverage-v8": "^3.1.1", 19 | "happy-dom": "^17.4.4", 20 | "tsdown": "^0.9.1", 21 | "typescript": "^5.8.3", 22 | "vitest": "^3.1.1" 23 | } 24 | }, 25 | "../../node_modules/.pnpm/@arethetypeswrong+cli@0.17.4/node_modules/@arethetypeswrong/cli": { 26 | "version": "0.17.4", 27 | "dev": true, 28 | "license": "MIT", 29 | "dependencies": { 30 | "@arethetypeswrong/core": "0.17.4", 31 | "chalk": "^4.1.2", 32 | "cli-table3": "^0.6.3", 33 | "commander": "^10.0.1", 34 | "marked": "^9.1.2", 35 | "marked-terminal": "^7.1.0", 36 | "semver": "^7.5.4" 37 | }, 38 | "bin": { 39 | "attw": "dist/index.js" 40 | }, 41 | "devDependencies": { 42 | "@types/marked": "^5.0.0", 43 | "@types/marked-terminal": "^3.1.3", 44 | "@types/node": "^22.5.0", 45 | "@types/semver": "^7.5.3", 46 | "ts-expose-internals": "5.6.1-rc" 47 | }, 48 | "engines": { 49 | "node": ">=18" 50 | } 51 | }, 52 | "../../node_modules/.pnpm/@changesets+cli@2.29.0/node_modules/@changesets/cli": { 53 | "version": "2.29.0", 54 | "dev": true, 55 | "license": "MIT", 56 | "dependencies": { 57 | "@changesets/apply-release-plan": "^7.0.10", 58 | "@changesets/assemble-release-plan": "^6.0.6", 59 | "@changesets/changelog-git": "^0.2.1", 60 | "@changesets/config": "^3.1.1", 61 | "@changesets/errors": "^0.2.0", 62 | "@changesets/get-dependents-graph": "^2.1.3", 63 | "@changesets/get-release-plan": "^4.0.8", 64 | "@changesets/git": "^3.0.2", 65 | "@changesets/logger": "^0.1.1", 66 | "@changesets/pre": "^2.0.2", 67 | "@changesets/read": "^0.6.3", 68 | "@changesets/should-skip-package": "^0.1.2", 69 | "@changesets/types": "^6.1.0", 70 | "@changesets/write": "^0.4.0", 71 | "@manypkg/get-packages": "^1.1.3", 72 | "ansi-colors": "^4.1.3", 73 | "ci-info": "^3.7.0", 74 | "enquirer": "^2.4.1", 75 | "external-editor": "^3.1.0", 76 | "fs-extra": "^7.0.1", 77 | "mri": "^1.2.0", 78 | "p-limit": "^2.2.0", 79 | "package-manager-detector": "^0.2.0", 80 | "picocolors": "^1.1.0", 81 | "resolve-from": "^5.0.0", 82 | "semver": "^7.5.3", 83 | "spawndamnit": "^3.0.1", 84 | "term-size": "^2.1.0" 85 | }, 86 | "bin": { 87 | "changeset": "bin.js" 88 | }, 89 | "devDependencies": { 90 | "@changesets/parse": "*", 91 | "@changesets/test-utils": "*", 92 | "@types/semver": "^7.5.0", 93 | "human-id": "^4.1.1", 94 | "outdent": "^0.5.0", 95 | "strip-ansi": "^5.2.0" 96 | } 97 | }, 98 | "../../node_modules/.pnpm/@types+node@20.17.30/node_modules/@types/node": { 99 | "version": "20.17.30", 100 | "dev": true, 101 | "license": "MIT", 102 | "dependencies": { 103 | "undici-types": "~6.19.2" 104 | } 105 | }, 106 | "../../node_modules/.pnpm/@vitest+coverage-v8@3.1.1_vitest@3.1.1_@types+node@20.17.30_happy-dom@17.4.4_jiti@2.4.2_/node_modules/@vitest/coverage-v8": { 107 | "version": "3.1.1", 108 | "dev": true, 109 | "license": "MIT", 110 | "dependencies": { 111 | "@ampproject/remapping": "^2.3.0", 112 | "@bcoe/v8-coverage": "^1.0.2", 113 | "debug": "^4.4.0", 114 | "istanbul-lib-coverage": "^3.2.2", 115 | "istanbul-lib-report": "^3.0.1", 116 | "istanbul-lib-source-maps": "^5.0.6", 117 | "istanbul-reports": "^3.1.7", 118 | "magic-string": "^0.30.17", 119 | "magicast": "^0.3.5", 120 | "std-env": "^3.8.1", 121 | "test-exclude": "^7.0.1", 122 | "tinyrainbow": "^2.0.0" 123 | }, 124 | "devDependencies": { 125 | "@types/debug": "^4.1.12", 126 | "@types/istanbul-lib-coverage": "^2.0.6", 127 | "@types/istanbul-lib-report": "^3.0.3", 128 | "@types/istanbul-lib-source-maps": "^4.0.4", 129 | "@types/istanbul-reports": "^3.0.4", 130 | "@types/test-exclude": "^6.0.2", 131 | "@vitest/browser": "3.1.1", 132 | "pathe": "^2.0.3", 133 | "v8-to-istanbul": "^9.3.0", 134 | "vite-node": "3.1.1", 135 | "vitest": "3.1.1" 136 | }, 137 | "funding": { 138 | "url": "https://opencollective.com/vitest" 139 | }, 140 | "peerDependencies": { 141 | "@vitest/browser": "3.1.1", 142 | "vitest": "3.1.1" 143 | }, 144 | "peerDependenciesMeta": { 145 | "@vitest/browser": { 146 | "optional": true 147 | } 148 | } 149 | }, 150 | "../../node_modules/.pnpm/happy-dom@17.4.4/node_modules/happy-dom": { 151 | "version": "17.4.4", 152 | "dev": true, 153 | "license": "MIT", 154 | "dependencies": { 155 | "webidl-conversions": "^7.0.0", 156 | "whatwg-mimetype": "^3.0.0" 157 | }, 158 | "devDependencies": { 159 | "@types/node": "^16.11.7", 160 | "@vitest/ui": "^2.1.4", 161 | "@webref/css": "6.6.2", 162 | "prettier": "^2.6.0", 163 | "typescript": "^5.0.4", 164 | "vitest": "^2.1.4" 165 | }, 166 | "engines": { 167 | "node": ">=18.0.0" 168 | } 169 | }, 170 | "../../node_modules/.pnpm/tsdown@0.9.1_typescript@5.8.3/node_modules/tsdown": { 171 | "version": "0.9.1", 172 | "dev": true, 173 | "license": "MIT", 174 | "dependencies": { 175 | "ansis": "^3.17.0", 176 | "cac": "^6.7.14", 177 | "chokidar": "^4.0.3", 178 | "consola": "^3.4.2", 179 | "debug": "^4.4.0", 180 | "diff": "^7.0.0", 181 | "find-up-simple": "^1.0.1", 182 | "rolldown": "^1.0.0-beta.7", 183 | "rolldown-plugin-dts": "^0.8.0", 184 | "tinyexec": "^1.0.1", 185 | "tinyglobby": "^0.2.12", 186 | "unconfig": "^7.3.1" 187 | }, 188 | "bin": { 189 | "tsdown": "dist/run.js" 190 | }, 191 | "devDependencies": { 192 | "@sxzz/eslint-config": "^6.1.1", 193 | "@sxzz/prettier-config": "^2.2.1", 194 | "@sxzz/test-utils": "^0.5.5", 195 | "@types/debug": "^4.1.12", 196 | "@types/diff": "^7.0.2", 197 | "@types/node": "^22.14.1", 198 | "@unocss/eslint-plugin": "66.1.0-beta.12", 199 | "bumpp": "^10.1.0", 200 | "eslint": "^9.25.0", 201 | "pkg-types": "^2.1.0", 202 | "prettier": "^3.5.3", 203 | "publint": "^0.3.12", 204 | "tsup": "^8.4.0", 205 | "tsx": "^4.19.3", 206 | "typedoc": "^0.28.2", 207 | "typedoc-plugin-markdown": "^4.6.2", 208 | "typescript": "~5.8.3", 209 | "unocss": "^66.1.0-beta.12", 210 | "unplugin-ast": "^0.14.6", 211 | "unplugin-unused": "^0.4.4", 212 | "vite": "^6.3.2", 213 | "vitepress": "^1.6.3", 214 | "vitepress-plugin-group-icons": "^1.5.2", 215 | "vitepress-plugin-llms": "^1.1.0", 216 | "vitest": "^3.1.1", 217 | "vue": "^3.5.13" 218 | }, 219 | "engines": { 220 | "node": ">=18.0.0" 221 | }, 222 | "funding": { 223 | "url": "https://github.com/sponsors/sxzz" 224 | }, 225 | "peerDependencies": { 226 | "publint": "^0.3.0", 227 | "unplugin-unused": "^0.4.0" 228 | }, 229 | "peerDependenciesMeta": { 230 | "publint": { 231 | "optional": true 232 | }, 233 | "unplugin-unused": { 234 | "optional": true 235 | } 236 | } 237 | }, 238 | "../../node_modules/.pnpm/typescript@5.8.3/node_modules/typescript": { 239 | "version": "5.8.3", 240 | "dev": true, 241 | "license": "Apache-2.0", 242 | "bin": { 243 | "tsc": "bin/tsc", 244 | "tsserver": "bin/tsserver" 245 | }, 246 | "devDependencies": { 247 | "@dprint/formatter": "^0.4.1", 248 | "@dprint/typescript": "0.93.3", 249 | "@esfx/canceltoken": "^1.0.0", 250 | "@eslint/js": "^9.17.0", 251 | "@octokit/rest": "^21.0.2", 252 | "@types/chai": "^4.3.20", 253 | "@types/diff": "^5.2.3", 254 | "@types/minimist": "^1.2.5", 255 | "@types/mocha": "^10.0.10", 256 | "@types/ms": "^0.7.34", 257 | "@types/node": "latest", 258 | "@types/source-map-support": "^0.5.10", 259 | "@types/which": "^3.0.4", 260 | "@typescript-eslint/rule-tester": "^8.18.1", 261 | "@typescript-eslint/type-utils": "^8.18.1", 262 | "@typescript-eslint/utils": "^8.18.1", 263 | "azure-devops-node-api": "^14.1.0", 264 | "c8": "^10.1.3", 265 | "chai": "^4.5.0", 266 | "chalk": "^4.1.2", 267 | "chokidar": "^3.6.0", 268 | "diff": "^5.2.0", 269 | "dprint": "^0.47.6", 270 | "esbuild": "^0.24.0", 271 | "eslint": "^9.17.0", 272 | "eslint-formatter-autolinkable-stylish": "^1.4.0", 273 | "eslint-plugin-regexp": "^2.7.0", 274 | "fast-xml-parser": "^4.5.1", 275 | "glob": "^10.4.5", 276 | "globals": "^15.13.0", 277 | "hereby": "^1.10.0", 278 | "jsonc-parser": "^3.3.1", 279 | "knip": "^5.41.0", 280 | "minimist": "^1.2.8", 281 | "mocha": "^10.8.2", 282 | "mocha-fivemat-progress-reporter": "^0.1.0", 283 | "monocart-coverage-reports": "^2.11.4", 284 | "ms": "^2.1.3", 285 | "playwright": "^1.49.1", 286 | "source-map-support": "^0.5.21", 287 | "tslib": "^2.8.1", 288 | "typescript": "^5.7.2", 289 | "typescript-eslint": "^8.18.1", 290 | "which": "^3.0.1" 291 | }, 292 | "engines": { 293 | "node": ">=14.17" 294 | } 295 | }, 296 | "../../node_modules/.pnpm/vitest@3.1.1_@types+node@20.17.30_happy-dom@17.4.4_jiti@2.4.2/node_modules/vitest": { 297 | "version": "3.1.1", 298 | "dev": true, 299 | "license": "MIT", 300 | "dependencies": { 301 | "@vitest/expect": "3.1.1", 302 | "@vitest/mocker": "3.1.1", 303 | "@vitest/pretty-format": "^3.1.1", 304 | "@vitest/runner": "3.1.1", 305 | "@vitest/snapshot": "3.1.1", 306 | "@vitest/spy": "3.1.1", 307 | "@vitest/utils": "3.1.1", 308 | "chai": "^5.2.0", 309 | "debug": "^4.4.0", 310 | "expect-type": "^1.2.0", 311 | "magic-string": "^0.30.17", 312 | "pathe": "^2.0.3", 313 | "std-env": "^3.8.1", 314 | "tinybench": "^2.9.0", 315 | "tinyexec": "^0.3.2", 316 | "tinypool": "^1.0.2", 317 | "tinyrainbow": "^2.0.0", 318 | "vite": "^5.0.0 || ^6.0.0", 319 | "vite-node": "3.1.1", 320 | "why-is-node-running": "^2.3.0" 321 | }, 322 | "bin": { 323 | "vitest": "vitest.mjs" 324 | }, 325 | "devDependencies": { 326 | "@ampproject/remapping": "^2.3.0", 327 | "@antfu/install-pkg": "^1.0.0", 328 | "@edge-runtime/vm": "^5.0.0", 329 | "@sinonjs/fake-timers": "14.0.0", 330 | "@types/debug": "^4.1.12", 331 | "@types/estree": "^1.0.7", 332 | "@types/istanbul-lib-coverage": "^2.0.6", 333 | "@types/istanbul-reports": "^3.0.4", 334 | "@types/jsdom": "^21.1.7", 335 | "@types/micromatch": "^4.0.9", 336 | "@types/node": "^22.13.13", 337 | "@types/prompts": "^2.4.9", 338 | "@types/sinonjs__fake-timers": "^8.1.5", 339 | "acorn-walk": "^8.3.4", 340 | "birpc": "0.2.19", 341 | "cac": "^6.7.14", 342 | "chai-subset": "^1.6.0", 343 | "find-up": "^6.3.0", 344 | "flatted": "^3.3.3", 345 | "get-tsconfig": "^4.10.0", 346 | "happy-dom": "^17.4.4", 347 | "jsdom": "^26.0.0", 348 | "local-pkg": "^1.1.1", 349 | "micromatch": "^4.0.8", 350 | "pretty-format": "^29.7.0", 351 | "prompts": "^2.4.2", 352 | "strip-literal": "^3.0.0", 353 | "tinyglobby": "^0.2.12", 354 | "ws": "^8.18.1" 355 | }, 356 | "engines": { 357 | "node": "^18.0.0 || ^20.0.0 || >=22.0.0" 358 | }, 359 | "funding": { 360 | "url": "https://opencollective.com/vitest" 361 | }, 362 | "peerDependencies": { 363 | "@edge-runtime/vm": "*", 364 | "@types/debug": "^4.1.12", 365 | "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", 366 | "@vitest/browser": "3.1.1", 367 | "@vitest/ui": "3.1.1", 368 | "happy-dom": "*", 369 | "jsdom": "*" 370 | }, 371 | "peerDependenciesMeta": { 372 | "@edge-runtime/vm": { 373 | "optional": true 374 | }, 375 | "@types/debug": { 376 | "optional": true 377 | }, 378 | "@types/node": { 379 | "optional": true 380 | }, 381 | "@vitest/browser": { 382 | "optional": true 383 | }, 384 | "@vitest/ui": { 385 | "optional": true 386 | }, 387 | "happy-dom": { 388 | "optional": true 389 | }, 390 | "jsdom": { 391 | "optional": true 392 | } 393 | } 394 | }, 395 | "node_modules/@arethetypeswrong/cli": { 396 | "resolved": "../../node_modules/.pnpm/@arethetypeswrong+cli@0.17.4/node_modules/@arethetypeswrong/cli", 397 | "link": true 398 | }, 399 | "node_modules/@changesets/cli": { 400 | "resolved": "../../node_modules/.pnpm/@changesets+cli@2.29.0/node_modules/@changesets/cli", 401 | "link": true 402 | }, 403 | "node_modules/@types/node": { 404 | "resolved": "../../node_modules/.pnpm/@types+node@20.17.30/node_modules/@types/node", 405 | "link": true 406 | }, 407 | "node_modules/@vitest/coverage-v8": { 408 | "resolved": "../../node_modules/.pnpm/@vitest+coverage-v8@3.1.1_vitest@3.1.1_@types+node@20.17.30_happy-dom@17.4.4_jiti@2.4.2_/node_modules/@vitest/coverage-v8", 409 | "link": true 410 | }, 411 | "node_modules/happy-dom": { 412 | "resolved": "../../node_modules/.pnpm/happy-dom@17.4.4/node_modules/happy-dom", 413 | "link": true 414 | }, 415 | "node_modules/react": { 416 | "version": "19.1.0", 417 | "resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz", 418 | "integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==", 419 | "license": "MIT", 420 | "engines": { 421 | "node": ">=0.10.0" 422 | } 423 | }, 424 | "node_modules/tsdown": { 425 | "resolved": "../../node_modules/.pnpm/tsdown@0.9.1_typescript@5.8.3/node_modules/tsdown", 426 | "link": true 427 | }, 428 | "node_modules/typescript": { 429 | "resolved": "../../node_modules/.pnpm/typescript@5.8.3/node_modules/typescript", 430 | "link": true 431 | }, 432 | "node_modules/vitest": { 433 | "resolved": "../../node_modules/.pnpm/vitest@3.1.1_@types+node@20.17.30_happy-dom@17.4.4_jiti@2.4.2/node_modules/vitest", 434 | "link": true 435 | } 436 | } 437 | } 438 | -------------------------------------------------------------------------------- /packages/with-react/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-react", 3 | "version": "1.1.2", 4 | "description": "Minimal open-source stack to help you ship an open-source package in TS", 5 | "main": "./dist/index.cjs", 6 | "module": "./dist/index.js", 7 | "types": "./dist/index.d.ts", 8 | "type": "module", 9 | "exports": { 10 | "./package.json": "./package.json", 11 | ".": { 12 | "import": { 13 | "types": "./dist/index.d.ts", 14 | "import": "./dist/index.js", 15 | "default": "./dist/index.js" 16 | }, 17 | "require": { 18 | "types": "./dist/index.d.cts", 19 | "import": "./dist/index.cjs", 20 | "require": "./dist/index.cjs" 21 | } 22 | } 23 | }, 24 | "scripts": { 25 | "test": "vitest", 26 | "test:cov": "vitest run --coverage", 27 | "postbuild": "pnpm run check:exports", 28 | "build": "tsdown src/index.ts --config tsdown.config.ts --clean", 29 | "dev": "tsdown src/index.ts --config tsdown.config.ts --watch", 30 | "prepublishOnly": "pnpm run build", 31 | "typecheck": "tsc", 32 | "validate": "pnpm run check && pnpm run typecheck && pnpm run test", 33 | "check:exports": "attw --pack .", 34 | "test:ui": "vitest --ui" 35 | }, 36 | "author": "", 37 | "license": "MIT", 38 | "repository": { 39 | "type": "git", 40 | "url": "git+https://github.com/jacobparis/with-react.git" 41 | }, 42 | "bugs": { 43 | "url": "https://github.com/jacobparis/with-react/issues" 44 | }, 45 | "files": [ 46 | "dist" 47 | ], 48 | "homepage": "https://github.com/jacobparis/with-react#readme", 49 | "publishConfig": { 50 | "provenance": true 51 | }, 52 | "devDependencies": { 53 | "@arethetypeswrong/cli": "^0.17.4", 54 | "@changesets/cli": "^2.29.0", 55 | "@testing-library/user-event": "^14.6.1", 56 | "@types/node": "^20.17.30", 57 | "@types/react": "^19.1.4", 58 | "@vitest/coverage-v8": "^3.1.1", 59 | "happy-dom": "^17.4.4", 60 | "tsdown": "^0.9.1", 61 | "typescript": "^5.8.3", 62 | "vitest": "^3.1.1" 63 | }, 64 | "peerDependencies": { 65 | "react": "^19.0.0" 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /packages/with-react/src/index.test.tsx: -------------------------------------------------------------------------------- 1 | import { describe, it, expect } from 'vitest' 2 | import React, { act, Suspense } from 'react' 3 | import { render, screen, waitFor } from '@testing-library/react' 4 | import userEvent from '@testing-library/user-event' 5 | import { WithState, WithCallback, WithDeferredValue, WithId, WithMemo, WithReducer, WithSyncExternalStore, WithTransition, WithFormStatus, WithUse } from './index.jsx' 6 | 7 | describe('WithState', () => { 8 | it('renders with initial state', () => { 9 | render( 10 | 11 | {(state) =>
Count: {state}
} 12 |
13 | ) 14 | expect(screen.getByText('Count: 42')).toBeDefined() 15 | }) 16 | 17 | it('updates state', async () => { 18 | const user = userEvent.setup() 19 | render( 20 | 21 | {(state, setState) => ( 22 |
23 |
Count: {state}
24 | 25 |
26 | )} 27 |
28 | ) 29 | expect(screen.getByText('Count: 42')).toBeDefined() 30 | await user.click(screen.getByText('Increment')) 31 | expect(screen.getByText('Count: 43')).toBeDefined() 32 | }) 33 | 34 | it('handles undefined initial state', async () => { 35 | const user = userEvent.setup() 36 | render( 37 | > 38 | {(state, setState) => ( 39 |
40 |
Count: {String(state)}
41 | 42 |
43 | )} 44 | 45 | ) 46 | expect(screen.getByText('Count: undefined')).toBeDefined() 47 | await user.click(screen.getByText('Set')) 48 | expect(screen.getByText('Count: 42')).toBeDefined() 49 | }) 50 | }) 51 | 52 | describe('WithCallback', () => { 53 | it('provides memoized callback', () => { 54 | let count = 0 55 | const callback = () => count++ 56 | render( 57 | 58 | {(memoizedCallback) => { 59 | memoizedCallback() 60 | return
Count: {count}
61 | }} 62 |
63 | ) 64 | expect(screen.getByText('Count: 1')).toBeDefined() 65 | }) 66 | }) 67 | 68 | describe('WithDeferredValue', () => { 69 | it('provides deferred value', () => { 70 | render( 71 | 72 | {(value) =>
Value: {value}
} 73 |
74 | ) 75 | expect(screen.getByText('Value: test')).toBeDefined() 76 | }) 77 | }) 78 | 79 | describe('WithId', () => { 80 | it('provides unique id', () => { 81 | render( 82 | 83 | {(id) =>
ID: {id}
} 84 |
85 | ) 86 | expect(screen.getByText(/^ID: /)).toBeDefined() 87 | }) 88 | }) 89 | 90 | describe('WithMemo', () => { 91 | it('provides memoized value', () => { 92 | render( 93 | 'test'}> 94 | {(value) =>
Value: {value}
} 95 |
96 | ) 97 | expect(screen.getByText('Value: test')).toBeDefined() 98 | }) 99 | }) 100 | 101 | describe('WithReducer', () => { 102 | it('provides state and dispatch', () => { 103 | render( 104 | state + 1} 106 | initialArg={0} 107 | > 108 | {(state, dispatch) => ( 109 |
110 |
Count: {state}
111 | 112 |
113 | )} 114 |
115 | ) 116 | expect(screen.getByText('Count: 0')).toBeDefined() 117 | }) 118 | }) 119 | 120 | describe('WithSyncExternalStore', () => { 121 | it('provides store value', () => { 122 | const store = { 123 | subscribe: () => () => {}, 124 | getSnapshot: () => 'test' 125 | } 126 | render( 127 | 128 | {(value) =>
Value: {value}
} 129 |
130 | ) 131 | expect(screen.getByText('Value: test')).toBeDefined() 132 | }) 133 | }) 134 | 135 | describe('WithTransition', () => { 136 | it('provides transition state and start function', () => { 137 | render( 138 | 139 | {(isPending, startTransition) => ( 140 |
141 |
Pending: {String(isPending)}
142 | 143 |
144 | )} 145 |
146 | ) 147 | expect(screen.getByText('Pending: false')).toBeDefined() 148 | }) 149 | }) 150 | 151 | // Getting weird errors with act() here, don't care enough to fix it right now 152 | describe.skip('WithFormStatus', () => { 153 | it('provides form status', async () => { 154 | const user = userEvent.setup() 155 | 156 | await act(async () => { 157 | render( 158 |
159 | 160 | {(status) => { 161 | console.log(status) 162 | return ( 163 |
164 |
Pending: {String(status.pending)}
165 |
Data: {String(status.data)}
166 |
Method: {status.method}
167 |
Action: {String(status.action)}
168 |
169 | ) 170 | }} 171 |
172 | 173 | 174 |
175 | ) 176 | }) 177 | 178 | await act(async () => { 179 | await user.click(screen.getByText('Submit')) 180 | }) 181 | 182 | await screen.findByText('Pending: true') 183 | // expect(screen.getByText('Data: null')).toBeDefined() 184 | // expect(screen.getByText('Method: get')).toBeDefined() 185 | // expect(screen.getByText('Action: null')).toBeDefined() 186 | }) 187 | }) 188 | 189 | const promise = Promise.resolve('test') 190 | 191 | describe('WithUse', async () => { 192 | it('provides resolved value', async () => { 193 | await act(async () => { 194 | render( 195 | Loading...}> 196 | 197 | {(value) =>
Value: {value}
} 198 |
199 |
200 | ) 201 | }) 202 | 203 | await screen.findByText('Value: test') 204 | }) 205 | }) 206 | -------------------------------------------------------------------------------- /packages/with-react/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { 2 | useActionState, 3 | useCallback, 4 | useDeferredValue, 5 | useId, 6 | useMemo, 7 | useReducer, 8 | useState, 9 | useSyncExternalStore, 10 | useTransition, 11 | use, 12 | } from 'react' 13 | import { useFormStatus } from 'react-dom' 14 | 15 | type ActionStateProps = Parameters> 16 | export function WithActionState({ 17 | children, 18 | action, 19 | initialState, 20 | permalink, 21 | }: { 22 | action: ActionStateProps[0] 23 | initialState: ActionStateProps[1] 24 | permalink?: ActionStateProps[2] 25 | children: (state: ReturnType>) => React.ReactNode 26 | }) { 27 | return children(useActionState(action, initialState, permalink)) 28 | } 29 | 30 | type CallbackProps unknown> = Parameters> 31 | export function WithCallback unknown>({ 32 | children, 33 | callback, 34 | deps = [], // default to empty array, missing deps array is always a bug 35 | }: { 36 | callback: CallbackProps[0] 37 | deps?: CallbackProps[1] 38 | children: (callback: ReturnType>) => React.ReactNode 39 | }) { 40 | return children(useCallback(callback, deps)) 41 | } 42 | 43 | type DeferredValueProps = Parameters> 44 | export function WithDeferredValue({ 45 | children, 46 | value, 47 | }: { 48 | value: DeferredValueProps[0] 49 | children: (value: ReturnType>) => React.ReactNode 50 | }) { 51 | return children(useDeferredValue(value)) 52 | } 53 | 54 | export function WithId({ 55 | children, 56 | }: { 57 | children: (id: ReturnType) => React.ReactNode 58 | }) { 59 | return children(useId()) 60 | } 61 | 62 | type MemoProps = Parameters> 63 | export function WithMemo({ 64 | children, 65 | compute, 66 | deps = [], // default to empty array, missing deps array is always a bug 67 | }: { 68 | compute: MemoProps[0] 69 | deps?: MemoProps[1] 70 | children: (value: ReturnType>) => React.ReactNode 71 | }) { 72 | return children(useMemo(compute, deps)) 73 | } 74 | 75 | export function WithReducer< 76 | State, 77 | InitialArg extends State, 78 | Action extends React.AnyActionArg 79 | >({ 80 | children, 81 | reducer, 82 | initialArg, 83 | init = (i: InitialArg) => i, 84 | }: { 85 | reducer: (prevState: State, ...args: Action) => State 86 | initialArg: InitialArg 87 | init?: (i: InitialArg) => State 88 | children: (state: State, dispatch: React.ActionDispatch) => React.ReactNode 89 | }) { 90 | const [state, dispatch] = useReducer(reducer, initialArg, init) 91 | return children(state, dispatch) 92 | } 93 | 94 | export function WithState({ 95 | children, 96 | initialState, 97 | }: { 98 | initialState?: StateValue | (() => StateValue) 99 | children: (state: StateValue | undefined, setState: React.Dispatch>) => React.ReactNode 100 | }) { 101 | const [state, setState] = useState(initialState) 102 | return children(state, setState) 103 | } 104 | 105 | type SyncExternalStoreProps = Parameters> 106 | export function WithSyncExternalStore({ 107 | children, 108 | subscribe, 109 | getSnapshot, 110 | getServerSnapshot, 111 | }: { 112 | subscribe: SyncExternalStoreProps[0] 113 | getSnapshot: SyncExternalStoreProps[1] 114 | getServerSnapshot?: SyncExternalStoreProps[2] 115 | children: (value: ReturnType>) => React.ReactNode 116 | }) { 117 | return children(useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)) 118 | } 119 | 120 | export function WithTransition({ 121 | children, 122 | }: { 123 | children: (isPending: ReturnType[0], startTransition: ReturnType[1]) => React.ReactNode 124 | }) { 125 | return children(...useTransition()) 126 | } 127 | 128 | export function WithFormStatus({ 129 | children, 130 | }: { 131 | children: (status: ReturnType) => React.ReactNode 132 | }) { 133 | return children(useFormStatus()) 134 | } 135 | 136 | type UseProps = Parameters> 137 | export function WithUse({ 138 | children, 139 | value, 140 | }: { 141 | value: UseProps[0] 142 | children: (value: Value) => React.ReactNode 143 | }) { 144 | return children(use(value)) 145 | } 146 | -------------------------------------------------------------------------------- /packages/with-react/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 4 | "moduleResolution": "Bundler", 5 | "module": "ESNext" /* Specify what module code is generated. */, 6 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 7 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 8 | "strict": true /* Enable all strict type-checking options. */, 9 | "skipLibCheck": true /* Skip type checking all .d.ts files. */, 10 | "types": ["vitest/globals"], 11 | "rootDir": ".", 12 | "outDir": "./dist", 13 | "noEmit": true, 14 | "jsx": "react" 15 | }, 16 | "include": ["src/**/*", "tests/**/*"], 17 | "exclude": ["node_modules", "dist"] 18 | } 19 | -------------------------------------------------------------------------------- /packages/with-react/tsdown.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "tsdown" 2 | 3 | export default defineConfig({ 4 | entry: ["src/index.ts"], 5 | sourcemap: true, 6 | dts: true, 7 | minify: false, 8 | format: ["esm", "cjs"], 9 | outDir: "dist", 10 | }) 11 | -------------------------------------------------------------------------------- /packages/with-react/vitest.config.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { defineConfig } from "vitest/config" 3 | 4 | export default defineConfig({ 5 | test: { 6 | environment: "happy-dom", 7 | globals: true, 8 | 9 | coverage: { 10 | all: false, 11 | provider: "v8", 12 | reporter: ["json-summary", "html"], 13 | thresholds: { 14 | statements: 80, 15 | branches: 80, 16 | functions: 80, 17 | lines: 80, 18 | }, 19 | }, 20 | }, 21 | }) 22 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - packages/* 3 | - test-apps/* 4 | onlyBuiltDependencies: 5 | - '@biomejs/biome' 6 | - esbuild 7 | - lefthook 8 | --------------------------------------------------------------------------------