├── .eslintignore ├── .eslintrc.json ├── .github ├── renovate.json └── workflows │ ├── ci.yml │ └── prettier.yml ├── .gitignore ├── .npmrc ├── .prettierignore ├── .releaserc.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.config.ts ├── package.json ├── pnpm-lock.yaml ├── pnpm-workspace.yaml ├── src ├── index.ts ├── useEffectEvent.test.tsx └── useEffectEvent.ts ├── test ├── react-18 │ ├── package.json │ ├── useEffectEvent.test.tsx │ └── vitest.config.ts └── react-experimental │ ├── package.json │ ├── useEffectEvent.test.tsx │ └── vitest.config.ts ├── tsconfig.base.json ├── tsconfig.build.json ├── tsconfig.json ├── vitest-cleanup-after-each.ts └── vitest.config.ts /.eslintignore: -------------------------------------------------------------------------------- 1 | dist -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "browser": true 5 | }, 6 | "parser": "@typescript-eslint/parser", 7 | "extends": ["plugin:@typescript-eslint/recommended", "prettier"], 8 | "reportUnusedDisableDirectives": true, 9 | "rules": { 10 | "simple-import-sort/imports": "error", 11 | "simple-import-sort/exports": "error", 12 | "prettier/prettier": "error", 13 | "@typescript-eslint/explicit-function-return-type": "off", 14 | "@typescript-eslint/no-var-requires": "off", 15 | "@typescript-eslint/no-unused-vars": "off", 16 | "@typescript-eslint/no-explicit-any": "off", 17 | "react-hooks/rules-of-hooks": "error", 18 | "react-hooks/exhaustive-deps": "error" 19 | }, 20 | "plugins": ["@typescript-eslint", "simple-import-sort", "prettier", "react", "react-hooks"] 21 | } 22 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": ["github>sanity-io/renovate-config"], 4 | "ignorePresets": ["github>sanity-io/renovate-config:group-non-major", ":ignoreModulesAndTests"], 5 | "packageRules": [ 6 | { 7 | "matchPackageNames": ["eslint-plugin-react-hooks"], 8 | "followTag": "experimental" 9 | }, 10 | { 11 | "matchFileNames": ["test/react-experimental/package.json"], 12 | "matchPackageNames": ["react", "react-dom"], 13 | "followTag": "experimental" 14 | }, 15 | { 16 | "matchFileNames": ["test/react-18/package.json"], 17 | "matchPackageNames": ["react", "react-dom"], 18 | "allowedVersions": "<=18" 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI & Release 2 | 3 | on: 4 | # Build on pushes branches that have a PR (including drafts) 5 | pull_request: 6 | # Build on commits pushed to branches without a PR if it's in the allowlist 7 | push: 8 | branches: [main] 9 | # https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow 10 | # https://github.com/sanity-io/semantic-release-preset/actions/workflows/ci.yml 11 | workflow_dispatch: 12 | inputs: 13 | release: 14 | description: "Publish new release" 15 | required: true 16 | default: false 17 | type: boolean 18 | 19 | concurrency: 20 | group: ${{ github.head_ref || github.run_id }} 21 | cancel-in-progress: true 22 | 23 | permissions: 24 | contents: read # for checkout 25 | 26 | jobs: 27 | build: 28 | runs-on: ubuntu-latest 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: pnpm/action-setup@v4 32 | - uses: actions/setup-node@v4 33 | with: 34 | node-version: lts/* 35 | - run: pnpm install 36 | - run: pnpm lint 37 | - run: pnpm test 38 | - run: pnpm prepare 39 | 40 | release: 41 | permissions: 42 | id-token: write # to enable use of OIDC for npm provenance 43 | needs: build 44 | if: always() && github.event.inputs.release == 'true' 45 | runs-on: ubuntu-latest 46 | steps: 47 | - uses: actions/create-github-app-token@v2 48 | id: app-token 49 | with: 50 | app-id: ${{ secrets.ECOSPARK_APP_ID }} 51 | private-key: ${{ secrets.ECOSPARK_APP_PRIVATE_KEY }} 52 | - uses: actions/checkout@v4 53 | with: 54 | # Need to fetch entire commit history to 55 | # analyze every commit since last release 56 | fetch-depth: 0 57 | # Uses generated token to allow pushing commits back 58 | token: ${{ steps.app-token.outputs.token }} 59 | # Make sure the value of GITHUB_TOKEN will not be persisted in repo's config 60 | persist-credentials: false 61 | - uses: pnpm/action-setup@v4 62 | - uses: actions/setup-node@v4 63 | with: 64 | node-version: lts/* 65 | - run: pnpm install 66 | - run: pnpm exec semantic-release 67 | # Don't allow interrupting the release step if the job is cancelled, as it can lead to an inconsistent state 68 | # e.g. git tags were pushed but it exited before `pnpm publish` 69 | if: always() 70 | env: 71 | NPM_CONFIG_PROVENANCE: true 72 | GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} 73 | NPM_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }} 74 | -------------------------------------------------------------------------------- /.github/workflows/prettier.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Prettier 3 | 4 | on: 5 | push: 6 | branches: [main] 7 | workflow_dispatch: 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} 11 | cancel-in-progress: true 12 | 13 | permissions: 14 | contents: read # for checkout 15 | 16 | jobs: 17 | run: 18 | name: Can the code be prettier? 🤔 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v4 22 | - uses: pnpm/action-setup@v4 23 | - uses: actions/setup-node@v4 24 | with: 25 | node-version: lts/* 26 | - run: pnpm install --dev --ignore-scripts 27 | - uses: actions/cache@v4 28 | with: 29 | path: node_modules/.cache/prettier/.prettier-cache 30 | key: prettier-${{ hashFiles('pnpm-lock.yaml') }}-${{ hashFiles('.prettierignore') }}-${{ hashFiles('package.json') }} 31 | - run: pnpm format 32 | - run: git restore .github/workflows pnpm-lock.yaml CHANGELOG.md 33 | - uses: actions/create-github-app-token@v2 34 | id: generate-token 35 | with: 36 | app-id: ${{ secrets.ECOSPARK_APP_ID }} 37 | private-key: ${{ secrets.ECOSPARK_APP_PRIVATE_KEY }} 38 | - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7 39 | with: 40 | author: github-actions <41898282+github-actions[bot]@users.noreply.github.com> 41 | body: I ran `pnpm format` 🧑‍💻 42 | branch: actions/prettier 43 | commit-message: "chore(prettier): 🤖 ✨" 44 | labels: 🤖 bot 45 | sign-commits: true 46 | title: "chore(prettier): 🤖 ✨" 47 | token: ${{ steps.generate-token.outputs.token }} 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .eslintcache 4 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | strict-peer-dependencies=false 2 | public-hoist-pattern=typescript 3 | public-hoist-pattern=vitest 4 | public-hoist-pattern=@vitejs/plugin-react 5 | public-hoist-pattern=@types/react 6 | public-hoist-pattern=@types/react-dom 7 | sync-injected-deps-after-scripts[]=install 8 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | pnpm-lock.yaml 3 | -------------------------------------------------------------------------------- /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@sanity/semantic-release-preset", 3 | "branches": ["main"] 4 | } 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 📓 Changelog 4 | 5 | All notable changes to this project will be documented in this file. See 6 | [Conventional Commits](https://conventionalcommits.org) for commit guidelines. 7 | 8 | ## [2.0.0](https://github.com/sanity-io/use-effect-event/compare/v1.0.2...v2.0.0) (2025-05-23) 9 | 10 | ### ⚠ BREAKING CHANGES 11 | 12 | - update useEffectEvent to be a better match for the native implementation (#22) 13 | 14 | ### Features 15 | 16 | - update useEffectEvent to be a better match for the native implementation ([#22](https://github.com/sanity-io/use-effect-event/issues/22)) ([23bde11](https://github.com/sanity-io/use-effect-event/commit/23bde11ebd3db42ef1c3d19426afce9dc53b6fef)) 17 | 18 | ### Bug Fixes 19 | 20 | - **docs:** add information about supported version of eslint-plugin-react-hooks ([#20](https://github.com/sanity-io/use-effect-event/issues/20)) ([873e9cb](https://github.com/sanity-io/use-effect-event/commit/873e9cb73dc5e1967e1b29fffd4a806df3276c68)) 21 | 22 | ## [1.0.2](https://github.com/sanity-io/use-effect-event/compare/v1.0.1...v1.0.2) (2024-07-10) 23 | 24 | ### Bug Fixes 25 | 26 | - **README:** update usage snippet ([#3](https://github.com/sanity-io/use-effect-event/issues/3)) ([e277205](https://github.com/sanity-io/use-effect-event/commit/e27720561df829e0ac931702bae1899931879df4)) 27 | 28 | ## [1.0.1](https://github.com/sanity-io/use-effect-event/compare/v1.0.0...v1.0.1) (2024-07-10) 29 | 30 | ### Bug Fixes 31 | 32 | - set publish config to `public` ([0901ef8](https://github.com/sanity-io/use-effect-event/commit/0901ef808069c2e29bd523e13b8b95b0dcf118e0)) 33 | 34 | ## 1.0.0 (2024-07-09) 35 | 36 | ### Features 37 | 38 | - initial release ([db1e7ce](https://github.com/sanity-io/use-effect-event/commit/db1e7cec92302a6ec74fb15643bfa40f82b76ce0)) 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Sanity 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 | [![CI & Release](https://github.com/sanity-io/use-effect-event/actions/workflows/ci.yml/badge.svg?event=push)](https://github.com/sanity-io/use-effect-event/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/use-effect-event.svg)](https://www.npmjs.com/package/use-effect-event) 2 | 3 | # use-effect-event 4 | 5 | > Ponyfill of the experimental `React.useEffectEvent` hook 6 | 7 | ## Usage 8 | 9 | > [!IMPORTANT] 10 | > Make sure you read about [the limitations and understand them](https://react.dev/learn/separating-events-from-effects#limitations-of-effect-events) before you start using this hook, it's not a silver bullet. 11 | 12 | This package implements the [same](https://react.dev/learn/separating-events-from-effects#declaring-an-effect-event) [API](https://react.dev/learn/separating-events-from-effects#reading-latest-props-and-state-with-effect-events) as the [experimental](https://19.react.dev/reference/react/experimental_useEffectEvent) `React.useEffectEvent` hook, based on its [implementation in Bluesky](https://github.com/bluesky-social/social-app/blob/ce0bf867ff3b50a495d8db242a7f55371bffeadc/src/lib/hooks/useNonReactiveCallback.ts#L3-L23). 13 | The only difference is that instead of installing an experimental build of React, you can use this package as a ponyfill. Here's an example, [from the official docs](https://react.dev/learn/separating-events-from-effects#reading-latest-props-and-state-with-effect-events), that shows how it can be used to log whenever `url` changes, and still access the latest value of `numberOfItems` without needing to resort to `useRef` proxying: 14 | 15 | ```tsx 16 | // import {useEffectEvent} from 'react' 17 | import {useEffectEvent} from 'use-effect-event' 18 | 19 | function Page({url}) { 20 | const {items} = useContext(ShoppingCartContext) 21 | const numberOfItems = items.length 22 | 23 | const onVisit = useEffectEvent((visitedUrl) => { 24 | logVisit(visitedUrl, numberOfItems) 25 | }) 26 | 27 | useEffect(() => { 28 | onVisit(url) 29 | }, [url]) 30 | } 31 | ``` 32 | 33 | ## Usage with `eslint-plugin-react-hooks` 34 | 35 | In order to use this hook with [`eslint-plugin-react-hooks`](npmjs.com/package/eslint-plugin-react-hooks), install `eslint-plugin-react-hooks@experimental`: 36 | 37 | ```json 38 | "devDependencies": { 39 | "eslint-plugin-react-hooks": "experimental" 40 | } 41 | ``` 42 | 43 | The experimental version of the `react-hooks` ESLint plugin checks that Effect Events are used according to the [rules](<(https://react.dev/learn/separating-events-from-effects#limitations-of-effect-events)>): 44 | 45 | 1. `useEffectEvent` functions are not passed between components (`react-hooks/rules-of-hooks`) 46 | 2. `useEffectEvent` functions are excluded from the dependency arrays of `useEffect` calls (`react-hooks/exhaustive-deps`) 47 | - this corrects the behavior of the stable version, which erroneously _requires_ that `useEffectEvent` functions are included as effect dependencies. 48 | -------------------------------------------------------------------------------- /package.config.ts: -------------------------------------------------------------------------------- 1 | import {defineConfig} from '@sanity/pkg-utils' 2 | 3 | export default defineConfig({ 4 | tsconfig: 'tsconfig.build.json', 5 | extract: { 6 | rules: { 7 | 'ae-forgotten-export': 'error', 8 | 'ae-incompatible-release-tags': 'warn', 9 | 'ae-internal-missing-underscore': 'off', 10 | }, 11 | }, 12 | }) 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-effect-event", 3 | "version": "2.0.0", 4 | "description": "Ponyfill of the experimental `React.useEffectEvent` hook", 5 | "keywords": [ 6 | "useEffectEvent", 7 | "useEvent", 8 | "hooks", 9 | "react", 10 | "react18", 11 | "react19", 12 | "sanity", 13 | "sanity-io", 14 | "typescript", 15 | "effect", 16 | "use" 17 | ], 18 | "bugs": { 19 | "url": "https://github.com/sanity-io/use-effect-event/issues" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/sanity-io/use-effect-event.git" 24 | }, 25 | "license": "MIT", 26 | "author": "Sanity.io ", 27 | "contributors": [ 28 | "Cody Olsen (https://github.com/stipsan)" 29 | ], 30 | "sideEffects": false, 31 | "type": "module", 32 | "exports": { 33 | ".": { 34 | "source": "./src/index.ts", 35 | "require": "./dist/index.cjs", 36 | "default": "./dist/index.js" 37 | }, 38 | "./package.json": "./package.json" 39 | }, 40 | "main": "./dist/index.cjs", 41 | "module": "./dist/index.js", 42 | "types": "./dist/index.d.ts", 43 | "files": [ 44 | "dist" 45 | ], 46 | "scripts": { 47 | "build": "pkg build --strict --clean --check", 48 | "format": "prettier --cache --write .", 49 | "lint": "eslint --cache .", 50 | "prepare": "pnpm build", 51 | "test": "vitest", 52 | "watch": "pnpm build -- --watch" 53 | }, 54 | "browserslist": "extends @sanity/browserslist-config", 55 | "prettier": "@sanity/prettier-config", 56 | "devDependencies": { 57 | "@sanity/pkg-utils": "^7.2.2", 58 | "@sanity/prettier-config": "^1.0.3", 59 | "@sanity/semantic-release-preset": "^5.0.0", 60 | "@testing-library/dom": "^10.4.0", 61 | "@testing-library/react": "^16.3.0", 62 | "@types/node": "^22.15.23", 63 | "@types/react": "^19.1.6", 64 | "@types/react-dom": "^19.1.5", 65 | "@typescript-eslint/eslint-plugin": "^8.33.0", 66 | "@typescript-eslint/parser": "^8.33.0", 67 | "@vitejs/plugin-react": "^4.5.0", 68 | "eslint": "^8.57.1", 69 | "eslint-config-prettier": "^10.1.5", 70 | "eslint-plugin-prettier": "^5.4.0", 71 | "eslint-plugin-react": "^7.37.5", 72 | "eslint-plugin-react-hooks": "0.0.0-experimental-f9ae0a4c-20250527", 73 | "eslint-plugin-simple-import-sort": "^12.1.1", 74 | "jsdom": "^26.1.0", 75 | "prettier": "^3.5.3", 76 | "prettier-plugin-packagejson": "^2.5.14", 77 | "react": "^19.1.0", 78 | "react-dom": "^19.1.0", 79 | "semantic-release": "^24.2.5", 80 | "typescript": "5.8.3", 81 | "vitest": "^3.1.4" 82 | }, 83 | "peerDependencies": { 84 | "react": "^18.3 || ^19.0.0-0" 85 | }, 86 | "packageManager": "pnpm@10.11.0", 87 | "publishConfig": { 88 | "access": "public" 89 | }, 90 | "pnpm": { 91 | "peerDependencyRules": { 92 | "allowAny": [ 93 | "react", 94 | "react-dom" 95 | ] 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - test/* 3 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './useEffectEvent' 2 | -------------------------------------------------------------------------------- /src/useEffectEvent.test.tsx: -------------------------------------------------------------------------------- 1 | import {render} from '@testing-library/react' 2 | import {useEffect, useInsertionEffect, useLayoutEffect, useRef, useState} from 'react' 3 | import {flushSync} from 'react-dom' 4 | import {describe, expect, test, vi} from 'vitest' 5 | 6 | import {useEffectEvent} from './useEffectEvent' 7 | 8 | test('useEffectEvent is always up-to-date with latest render', () => { 9 | const stack: Array = [] 10 | const Component = () => { 11 | const [count, setCount] = useState(0) 12 | const logCount = useEffectEvent(() => { 13 | stack.push(count) 14 | }) 15 | 16 | return ( 17 | 28 | ) 29 | } 30 | 31 | const {container} = render() 32 | container.querySelector('button')!.click() 33 | 34 | // 0,0,2 because: 35 | // 0 -> before the update, so base value 36 | // 0 -> technically after the 1st call of `setCount`, but the component didn’t re-render yet, so `count` wasn't updated 37 | // 2 -> as we call `flushSync`, the component updates, and the two different setCount get applied 38 | expect(stack).toEqual([0, 0, 2]) 39 | }) 40 | 41 | describe('render cycle', () => { 42 | test('functions created by useEffectEvent cannot be called in render', () => { 43 | vi.spyOn(console, 'error').mockImplementation(() => {}) 44 | const Component = () => { 45 | const onRender = useEffectEvent(() => {}) 46 | onRender() 47 | 48 | return null 49 | } 50 | 51 | expect(() => render()).toThrow( 52 | "A function wrapped in useEffectEvent can't be called during rendering.", 53 | ) 54 | }) 55 | 56 | test('functions created by useEffectEvent cannot be called in re-renders', () => { 57 | const Component = () => { 58 | const isInitialRenderRef = useRef(true) 59 | useEffect(() => { 60 | isInitialRenderRef.current = false 61 | }) 62 | const onRender = useEffectEvent(() => {}) 63 | 64 | if (!isInitialRenderRef.current) { 65 | onRender() 66 | } 67 | 68 | return null 69 | } 70 | 71 | const {rerender} = render() 72 | 73 | expect(() => rerender()).toThrow( 74 | "A function wrapped in useEffectEvent can't be called during rendering.", 75 | ) 76 | }) 77 | }) 78 | 79 | test('useEffectEvent creates functions with unstable references (they change at each render)', () => { 80 | const stack: Array<() => void> = [] 81 | const Component = () => { 82 | const event = useEffectEvent(() => {}) 83 | stack.push(event) 84 | 85 | return null 86 | } 87 | 88 | const {rerender} = render() 89 | rerender() 90 | 91 | expect(stack).toHaveLength(2) 92 | expect(stack[0]).not.toBe(stack[1]) 93 | }) 94 | 95 | test('useEffectEvent’s created function can be called in all use*Effect without throwing', () => { 96 | const stack: Array = [] 97 | const Component = () => { 98 | const logToStack = useEffectEvent((event: string) => { 99 | stack.push(event) 100 | }) 101 | 102 | // logToStack should also be omitted by the linter from all of those dependencies 103 | // For now, only enabled in the experimental build of `eslint-plugin-react-hooks` 104 | useInsertionEffect(() => { 105 | logToStack('useInsertionEffect') 106 | }, []) 107 | useLayoutEffect(() => { 108 | logToStack('useLayoutEffect') 109 | }, []) 110 | useEffect(() => { 111 | logToStack('useEffect') 112 | }, []) 113 | 114 | return null 115 | } 116 | 117 | render() 118 | 119 | expect(stack).toEqual(['useInsertionEffect', 'useLayoutEffect', 'useEffect']) 120 | }) 121 | 122 | test('useEffectEvent’s created function can be called in all use*Effect without throwing in strict mode', () => { 123 | const stack: Array = [] 124 | const Component = () => { 125 | const logToStack = useEffectEvent((event: string) => { 126 | stack.push(event) 127 | }) 128 | 129 | // logToStack should also be omitted by the linter from all of those dependencies 130 | // For now, only enabled in the experimental build of `eslint-plugin-react-hooks` 131 | useInsertionEffect(() => { 132 | logToStack('useInsertionEffect') 133 | }, []) 134 | useLayoutEffect(() => { 135 | logToStack('useLayoutEffect') 136 | }, []) 137 | useEffect(() => { 138 | logToStack('useEffect') 139 | }, []) 140 | 141 | return null 142 | } 143 | 144 | render(, {reactStrictMode: true}) 145 | 146 | expect(stack).toEqual([ 147 | 'useInsertionEffect', 148 | 'useLayoutEffect', 149 | 'useEffect', 150 | 'useLayoutEffect', 151 | 'useEffect', 152 | ]) 153 | }) 154 | -------------------------------------------------------------------------------- /src/useEffectEvent.ts: -------------------------------------------------------------------------------- 1 | import {useInsertionEffect, useRef} from 'react' 2 | 3 | function forbiddenInRender() { 4 | throw new Error("A function wrapped in useEffectEvent can't be called during rendering.") 5 | } 6 | 7 | /** 8 | * This is a ponyfill of the upcoming `useEffectEvent` hook that'll arrive in React 19. 9 | * https://19.react.dev/learn/separating-events-from-effects#declaring-an-effect-event 10 | * To learn more about the ponyfill itself, see: https://blog.bitsrc.io/a-look-inside-the-useevent-polyfill-from-the-new-react-docs-d1c4739e8072 11 | * @public 12 | */ 13 | export function useEffectEvent void>(fn: T): T { 14 | const ref = useRef(null) 15 | ref.current = forbiddenInRender as T 16 | 17 | useInsertionEffect(() => { 18 | ref.current = fn 19 | }, [fn]) 20 | 21 | return ((...args: any) => { 22 | const latestFn = ref.current! 23 | return latestFn(...args) 24 | }) as T 25 | } 26 | -------------------------------------------------------------------------------- /test/react-18/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test-react-18", 3 | "version": "0.0.0", 4 | "private": true, 5 | "dependencies": { 6 | "react": "18.3.1", 7 | "react-dom": "18.3.1" 8 | }, 9 | "devDependencies": { 10 | "@testing-library/dom": "^10.4.0", 11 | "@testing-library/react": "^16.3.0" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/react-18/useEffectEvent.test.tsx: -------------------------------------------------------------------------------- 1 | import {render} from '@testing-library/react' 2 | import {useEffect, useInsertionEffect, useLayoutEffect, useRef, useState} from 'react' 3 | import {flushSync} from 'react-dom' 4 | import {describe, expect, test, vi} from 'vitest' 5 | 6 | import {useEffectEvent} from '../../src/useEffectEvent' 7 | 8 | test('useEffectEvent is always up-to-date with latest render', () => { 9 | const stack: Array = [] 10 | const Component = () => { 11 | const [count, setCount] = useState(0) 12 | const logCount = useEffectEvent(() => { 13 | stack.push(count) 14 | }) 15 | 16 | return ( 17 | 28 | ) 29 | } 30 | 31 | const {container} = render() 32 | container.querySelector('button')!.click() 33 | 34 | // 0,0,2 because: 35 | // 0 -> before the update, so base value 36 | // 0 -> technically after the 1st call of `setCount`, but the component didn’t re-render yet, so `count` wasn't updated 37 | // 2 -> as we call `flushSync`, the component updates, and the two different setCount get applied 38 | expect(stack).toEqual([0, 0, 2]) 39 | }) 40 | 41 | describe('render cycle', () => { 42 | test('functions created by useEffectEvent cannot be called in render', () => { 43 | vi.spyOn(console, 'error').mockImplementation(() => {}) 44 | const Component = () => { 45 | const onRender = useEffectEvent(() => {}) 46 | onRender() 47 | 48 | return null 49 | } 50 | 51 | expect(() => render()).toThrow( 52 | "A function wrapped in useEffectEvent can't be called during rendering.", 53 | ) 54 | }) 55 | 56 | test('functions created by useEffectEvent cannot be called in re-renders', () => { 57 | const Component = () => { 58 | const isInitialRenderRef = useRef(true) 59 | useEffect(() => { 60 | isInitialRenderRef.current = false 61 | }) 62 | const onRender = useEffectEvent(() => {}) 63 | 64 | if (!isInitialRenderRef.current) { 65 | onRender() 66 | } 67 | 68 | return null 69 | } 70 | 71 | const {rerender} = render() 72 | 73 | expect(() => rerender()).toThrow( 74 | "A function wrapped in useEffectEvent can't be called during rendering.", 75 | ) 76 | }) 77 | }) 78 | 79 | test('useEffectEvent creates functions with unstable references (they change at each render)', () => { 80 | const stack: Array<() => void> = [] 81 | const Component = () => { 82 | const event = useEffectEvent(() => {}) 83 | stack.push(event) 84 | 85 | return null 86 | } 87 | 88 | const {rerender} = render() 89 | rerender() 90 | 91 | expect(stack).toHaveLength(2) 92 | expect(stack[0]).not.toBe(stack[1]) 93 | }) 94 | 95 | test('useEffectEvent’s created function can be called in all use*Effect without throwing', () => { 96 | const stack: Array = [] 97 | const Component = () => { 98 | const logToStack = useEffectEvent((event: string) => { 99 | stack.push(event) 100 | }) 101 | 102 | // logToStack should also be omitted by the linter from all of those dependencies 103 | // For now, only enabled in the experimental build of `eslint-plugin-react-hooks` 104 | useInsertionEffect(() => { 105 | logToStack('useInsertionEffect') 106 | }, []) 107 | useLayoutEffect(() => { 108 | logToStack('useLayoutEffect') 109 | }, []) 110 | useEffect(() => { 111 | logToStack('useEffect') 112 | }, []) 113 | 114 | return null 115 | } 116 | 117 | render() 118 | 119 | expect(stack).toEqual(['useInsertionEffect', 'useLayoutEffect', 'useEffect']) 120 | }) 121 | 122 | test('useEffectEvent’s created function can be called in all use*Effect without throwing in strict mode', () => { 123 | const stack: Array = [] 124 | const Component = () => { 125 | const logToStack = useEffectEvent((event: string) => { 126 | stack.push(event) 127 | }) 128 | 129 | // logToStack should also be omitted by the linter from all of those dependencies 130 | // For now, only enabled in the experimental build of `eslint-plugin-react-hooks` 131 | useInsertionEffect(() => { 132 | logToStack('useInsertionEffect') 133 | }, []) 134 | useLayoutEffect(() => { 135 | logToStack('useLayoutEffect') 136 | }, []) 137 | useEffect(() => { 138 | logToStack('useEffect') 139 | }, []) 140 | 141 | return null 142 | } 143 | 144 | render(, {reactStrictMode: true}) 145 | 146 | expect(stack).toEqual([ 147 | 'useInsertionEffect', 148 | 'useLayoutEffect', 149 | 'useEffect', 150 | 'useLayoutEffect', 151 | 'useEffect', 152 | ]) 153 | }) 154 | -------------------------------------------------------------------------------- /test/react-18/vitest.config.ts: -------------------------------------------------------------------------------- 1 | import react from '@vitejs/plugin-react' 2 | import {defineConfig} from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | plugins: [react()], 6 | test: { 7 | name: 'react 18', 8 | environment: 'jsdom', 9 | setupFiles: ['../../vitest-cleanup-after-each.ts'], 10 | }, 11 | }) 12 | -------------------------------------------------------------------------------- /test/react-experimental/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test-react-experimental", 3 | "version": "0.0.0", 4 | "private": true, 5 | "dependencies": { 6 | "react": "0.0.0-experimental-f9ae0a4c-20250527", 7 | "react-dom": "0.0.0-experimental-f9ae0a4c-20250527" 8 | }, 9 | "devDependencies": { 10 | "@testing-library/dom": "^10.4.0", 11 | "@testing-library/react": "^16.3.0" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/react-experimental/useEffectEvent.test.tsx: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import {render} from '@testing-library/react' 4 | import { 5 | experimental_useEffectEvent, 6 | useEffect, 7 | useInsertionEffect, 8 | useLayoutEffect, 9 | useRef, 10 | useState, 11 | } from 'react' 12 | import {flushSync} from 'react-dom' 13 | import {describe, expect, test, vi} from 'vitest' 14 | 15 | import {useEffectEvent} from '../../src/useEffectEvent' 16 | 17 | describe.each([ 18 | ['native useEffectEvent', experimental_useEffectEvent], 19 | ['ponyfill useEffectEvent', useEffectEvent], 20 | ])('implementation: %s', (_, useEffectEvent) => { 21 | test('useEffectEvent is always up-to-date with latest render', () => { 22 | const stack: Array = [] 23 | const Component = () => { 24 | const [count, setCount] = useState(0) 25 | const logCount = useEffectEvent(() => { 26 | stack.push(count) 27 | }) 28 | 29 | return ( 30 | 41 | ) 42 | } 43 | 44 | const {container} = render() 45 | container.querySelector('button')!.click() 46 | 47 | // 0,0,2 because: 48 | // 0 -> before the update, so base value 49 | // 0 -> technically after the 1st call of `setCount`, but the component didn’t re-render yet, so `count` wasn't updated 50 | // 2 -> as we call `flushSync`, the component updates, and the two different setCount get applied 51 | expect(stack).toEqual([0, 0, 2]) 52 | }) 53 | 54 | describe('render cycle', () => { 55 | test('functions created by useEffectEvent cannot be called in render', () => { 56 | vi.spyOn(console, 'error').mockImplementation(() => {}) 57 | const Component = () => { 58 | const onRender = useEffectEvent(() => {}) 59 | onRender() 60 | 61 | return null 62 | } 63 | 64 | expect(() => render()).toThrow( 65 | "A function wrapped in useEffectEvent can't be called during rendering.", 66 | ) 67 | }) 68 | 69 | test('functions created by useEffectEvent cannot be called in re-renders', () => { 70 | const Component = () => { 71 | const isInitialRenderRef = useRef(true) 72 | useEffect(() => { 73 | isInitialRenderRef.current = false 74 | }) 75 | const onRender = useEffectEvent(() => {}) 76 | 77 | if (!isInitialRenderRef.current) { 78 | onRender() 79 | } 80 | 81 | return null 82 | } 83 | 84 | const {rerender} = render() 85 | 86 | expect(() => rerender()).toThrow( 87 | "A function wrapped in useEffectEvent can't be called during rendering.", 88 | ) 89 | }) 90 | }) 91 | 92 | test('useEffectEvent creates functions with unstable references (they change at each render)', () => { 93 | const stack: Array<() => void> = [] 94 | const Component = () => { 95 | const event = useEffectEvent(() => {}) 96 | stack.push(event) 97 | 98 | return null 99 | } 100 | 101 | const {rerender} = render() 102 | rerender() 103 | 104 | expect(stack).toHaveLength(2) 105 | expect(stack[0]).not.toBe(stack[1]) 106 | }) 107 | 108 | test('useEffectEvent’s created function can be called in all use*Effect without throwing', () => { 109 | const stack: Array = [] 110 | const Component = () => { 111 | const logToStack = useEffectEvent((event: string) => { 112 | stack.push(event) 113 | }) 114 | 115 | // logToStack should also be omitted by the linter from all of those dependencies 116 | // For now, only enabled in the experimental build of `eslint-plugin-react-hooks` 117 | useInsertionEffect(() => { 118 | logToStack('useInsertionEffect') 119 | }, []) 120 | useLayoutEffect(() => { 121 | logToStack('useLayoutEffect') 122 | }, []) 123 | useEffect(() => { 124 | logToStack('useEffect') 125 | }, []) 126 | 127 | return null 128 | } 129 | 130 | render() 131 | 132 | expect(stack).toEqual(['useInsertionEffect', 'useLayoutEffect', 'useEffect']) 133 | }) 134 | 135 | test('useEffectEvent’s created function can be called in all use*Effect without throwing in strict mode', () => { 136 | const stack: Array = [] 137 | const Component = () => { 138 | const logToStack = useEffectEvent((event: string) => { 139 | stack.push(event) 140 | }) 141 | 142 | // logToStack should also be omitted by the linter from all of those dependencies 143 | // For now, only enabled in the experimental build of `eslint-plugin-react-hooks` 144 | useInsertionEffect(() => { 145 | logToStack('useInsertionEffect') 146 | }, []) 147 | useLayoutEffect(() => { 148 | logToStack('useLayoutEffect') 149 | }, []) 150 | useEffect(() => { 151 | logToStack('useEffect') 152 | }, []) 153 | 154 | return null 155 | } 156 | 157 | render(, {reactStrictMode: true}) 158 | 159 | expect(stack).toEqual([ 160 | 'useInsertionEffect', 161 | 'useLayoutEffect', 162 | 'useEffect', 163 | 'useLayoutEffect', 164 | 'useEffect', 165 | ]) 166 | }) 167 | }) 168 | -------------------------------------------------------------------------------- /test/react-experimental/vitest.config.ts: -------------------------------------------------------------------------------- 1 | import react from '@vitejs/plugin-react' 2 | import {defineConfig} from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | plugins: [react()], 6 | test: { 7 | name: 'react experimental', 8 | environment: 'jsdom', 9 | setupFiles: ['../../vitest-cleanup-after-each.ts'], 10 | }, 11 | }) 12 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@sanity/pkg-utils/tsconfig/strictest.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "dist" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base", 3 | "include": ["src/**/*.ts", "src/**/*.tsx"], 4 | "exclude": ["dist", "node_modules", "./src/**/*.test.ts", "./src/**/*.test.tsx"] 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base", 3 | "include": ["**/*.ts", "**/*.tsx"], 4 | "exclude": ["dist", "node_modules"] 5 | } 6 | -------------------------------------------------------------------------------- /vitest-cleanup-after-each.ts: -------------------------------------------------------------------------------- 1 | import {cleanup} from '@testing-library/react' 2 | import {afterEach} from 'vitest' 3 | 4 | afterEach(() => { 5 | cleanup() 6 | }) 7 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import react from '@vitejs/plugin-react' 2 | import {defineConfig} from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | plugins: [react()], 6 | test: { 7 | setupFiles: ['vitest-cleanup-after-each.ts'], 8 | environment: 'jsdom', 9 | workspace: [ 10 | 'test/*', 11 | { 12 | extends: true, 13 | test: {name: 'react 19', include: ['src/**\/*.{test,spec}.?(c|m)[jt]s?(x)']}, 14 | }, 15 | ], 16 | }, 17 | }) 18 | --------------------------------------------------------------------------------