Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore(studio): migrate useStaticEffectEvent to React 19 useEffectEvent (#46415)

Alaister Young7e9badc6b82c
diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md
index 6fe68cc8e93..ca29fe71fba 100644
--- a/.claude/CLAUDE.md
+++ b/.claude/CLAUDE.md
@@ -6,7 +6,7 @@ pnpm 10 + Turborepo monorepo. Requires Node >= 22.
| Directory | Purpose |
| ----------------- | ------------------------------------------------------------ |
-| `apps/studio` | Supabase Studio/Dashboard — Next.js (pages router), React 18 |
+| `apps/studio` | Supabase Studio/Dashboard — Next.js (pages router), React 19 |
| `apps/docs` | Documentation site |
| `apps/www` | Marketing website |
| `packages/ui` | Shared UI components (shadcn/ui based) |
diff --git a/.claude/skills/use-static-effect-event/SKILL.md b/.claude/skills/use-static-effect-event/SKILL.md
deleted file mode 100644
index a707bafe42b..00000000000
--- a/.claude/skills/use-static-effect-event/SKILL.md
+++ /dev/null
@@ -1,141 +0,0 @@
----
-name: use-static-effect-event
-description: useStaticEffectEvent hook in Supabase Studio — a userland polyfill for
- React's useEffectEvent. Use when you need to read latest state/props inside a useEffect
- without re-triggering it, or when stale closures in Effects are causing bugs.
----
-
-# useStaticEffectEvent
-
-Located at `apps/studio/hooks/useStaticEffectEvent.ts`.
-
-A userland polyfill for React's `useEffectEvent` (stable in React 19.2). It solves the stale closure problem: gives you a **stable callback** that always reads the latest props/state without those values triggering Effect re-runs.
-
-## The Problem It Solves
-
-Without it, you face two bad options inside `useEffect`:
-
-1. **Add values to dependencies** → unnecessary Effect re-runs (teardown/reconnect)
-2. **Omit from dependencies** → stale closure bugs (outdated values)
-
-```tsx
-// Problem: re-runs every time `theme` changes, even though we only
-// want to reconnect when `roomId` changes
-useEffect(() => {
- const connection = createConnection(roomId)
- connection.on('connected', () => {
- showNotification('Connected!', theme) // theme causes unwanted reconnects
- })
- return () => connection.disconnect()
-}, [roomId, theme])
-```
-
-## When to Use
-
-1. Read latest state/props inside an Effect without re-triggering it
-2. Create stable callbacks that always use current values
-3. Avoid stale closures in event handlers used within Effects
-
-### Pattern 1: Sync data without re-running on every change
-
-```tsx
-const syncApiPrivileges = useStaticEffectEvent(() => {
- if (hasLoadedInitialData.current) return
- if (!apiAccessStatus.isSuccess) return
- if (!privilegesForTable) return
-
- hasLoadedInitialData.current = true
- setPrivileges(privilegesForTable.privileges)
-})
-
-useEffect(() => {
- syncApiPrivileges()
-}, [apiAccessStatus.status, syncApiPrivileges])
-```
-
-### Pattern 2: Stable callbacks for async operations
-
-```tsx
-const exportInternal = useStaticEffectEvent(
- async ({ bypassConfirmation }: { bypassConfirmation: boolean }) => {
- if (!params.enabled) return
- const { projectRef, connectionString, entity, totalRows } = params
- // complex async logic using latest params
- }
-)
-
-// Stable reference — safe to use in useCallback
-const exportInDesiredFormat = useCallback(
- () => exportInternal({ bypassConfirmation: false }),
- [exportInternal]
-)
-```
-
-### Pattern 3: Infinite scroll / pagination triggers
-
-```tsx
-const fetchNext = useStaticEffectEvent(() => {
- if (lastItem && lastItem.index >= items.length - 1 && hasNextPage && !isFetchingNextPage) {
- fetchNextPage()
- }
-})
-
-useEffect(fetchNext, [lastItem, fetchNext])
-```
-
-## When NOT to Use
-
-**Don't use it to hide legitimate dependencies:**
-
-```tsx
-// ❌ Bad — roomId IS a legitimate dependency; this hides a bug
-const connect = useStaticEffectEvent(() => {
- const connection = createConnection(roomId)
- connection.connect()
-})
-useEffect(() => {
- connect()
-}, [connect]) // Won't reconnect when roomId changes!
-
-// ✅ roomId belongs in deps
-useEffect(() => {
- const connection = createConnection(roomId)
- connection.connect()
- return () => connection.disconnect()
-}, [roomId])
-```
-
-**Don't use it for simple event handlers outside Effects:**
-
-```tsx
-// ❌ Unnecessary — not used inside an Effect
-const handleClick = useStaticEffectEvent(() => console.log(count))
-
-// ✅ Regular function is fine
-const handleClick = () => console.log(count)
-```
-
-## Rules
-
-1. Only call the returned function **inside Effects** (`useEffect`, `useLayoutEffect`)
-2. Don't pass it to other components or hooks as a callback prop
-3. Use for **non-reactive logic only** — reads values but shouldn't trigger re-runs
-4. **Include it in dependency arrays** when used in `useEffect` (it's stable, won't cause re-runs)
-
-## How It Works
-
-```tsx
-export const useStaticEffectEvent = <Callback extends Function>(callback: Callback) => {
- const callbackRef = useRef(callback)
-
- useLayoutEffect(() => {
- callbackRef.current = callback // always latest
- })
-
- const eventFn = useCallback((...args: any) => {
- return callbackRef.current(...args)
- }, []) // stable reference
-
- return eventFn as unknown as Callback
-}
-```
diff --git a/.claude/skills/vercel-composition-patterns/SKILL.md b/.claude/skills/vercel-composition-patterns/SKILL.md
index c1fea6c11e3..afde8507fad 100644
--- a/.claude/skills/vercel-composition-patterns/SKILL.md
+++ b/.claude/skills/vercel-composition-patterns/SKILL.md
@@ -63,7 +63,7 @@ Reference these guidelines when:
### 4. React 19 APIs (MEDIUM)
-> **⚠️ React 19+ only.** Supabase Studio currently uses React 18 — skip these patterns in Studio code.
+> **⚠️ React 19+ only.** Skip these patterns if you're on React 18 or earlier.
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
diff --git a/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx b/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx
index dac3e8c1887..b7db625bdda 100644
--- a/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx
+++ b/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx
@@ -1,6 +1,6 @@
import { format } from 'date-fns'
import { Loader2 } from 'lucide-react'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react'
import { AiIconAnimation, Button, Calendar } from 'ui'
import {
CustomOptionProps,
@@ -18,7 +18,6 @@ import { columnToFilterProperty } from './FilterPopoverNew.utils'
import { useTableFilter } from '@/components/grid/hooks/useTableFilter'
import type { Filter } from '@/components/grid/types'
import { useSqlFilterGenerateMutation } from '@/data/ai/sql-filter-mutation'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { useTableEditorTableStateSnapshot } from '@/state/table-editor-table'
export interface FilterPopoverProps {
@@ -138,13 +137,14 @@ export const FilterPopoverNew = ({
// so transient edits don't fire data requests.
const [filterGroup, setFilterGroup] = useState<FilterGroup>(() => filtersToFilterGroup(filters))
- const syncFromFilters = useStaticEffectEvent(() => {
+ const syncFromFilters = useEffectEvent(() => {
setFilterGroup(filtersToFilterGroup(filters))
})
useEffect(() => {
syncFromFilters()
- }, [filters, syncFromFilters])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [filters])
const columns = useMemo(() => snap.table?.columns ?? [], [snap.table?.columns])
diff --git a/apps/studio/components/grid/hooks/useFilterLifeCycle.ts b/apps/studio/components/grid/hooks/useFilterLifeCycle.ts
index 68d58c10d69..934bae3df11 100644
--- a/apps/studio/components/grid/hooks/useFilterLifeCycle.ts
+++ b/apps/studio/components/grid/hooks/useFilterLifeCycle.ts
@@ -1,8 +1,7 @@
-import { useEffect, useRef } from 'react'
+import { useEffect, useEffectEvent, useRef } from 'react'
import { filtersToUrlParams, formatFilterURLParams } from '../SupabaseGrid.utils'
import { useTableEditorFiltersSort } from '@/hooks/misc/useTableEditorFiltersSort'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { useTableEditorTableStateSnapshot } from '@/state/table-editor-table'
/**
@@ -14,7 +13,7 @@ export function useInitializeFiltersFromUrl() {
const snap = useTableEditorTableStateSnapshot()
const { filters: urlFilters } = useTableEditorFiltersSort()
- const initializeFilters = useStaticEffectEvent(() => {
+ const initializeFilters = useEffectEvent(() => {
const parsedFilters = formatFilterURLParams(urlFilters)
if (parsedFilters.length > 0) {
snap.setFilters(parsedFilters)
@@ -23,7 +22,8 @@ export function useInitializeFiltersFromUrl() {
useEffect(() => {
initializeFilters()
- }, [initializeFilters])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [])
}
/**
diff --git a/apps/studio/components/interfaces/ApiAuthorization/ApiAuthorization.Valid.tsx b/apps/studio/components/interfaces/ApiAuthorization/ApiAuthorization.Valid.tsx
index bf81214439b..8f6ebdf5517 100644
--- a/apps/studio/components/interfaces/ApiAuthorization/ApiAuthorization.Valid.tsx
+++ b/apps/studio/components/interfaces/ApiAuthorization/ApiAuthorization.Valid.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import { useEffect, useMemo, useState, type ReactNode } from 'react'
+import { useEffect, useEffectEvent, useMemo, useState, type ReactNode } from 'react'
import { useForm, type UseFormReturn } from 'react-hook-form'
import { toast } from 'sonner'
@@ -16,7 +16,6 @@ import { useApiAuthorizationApproveMutation } from '@/data/api-authorization/api
import { useApiAuthorizationDeclineMutation } from '@/data/api-authorization/api-authorization-decline-mutation'
import { useApiAuthorizationQuery } from '@/data/api-authorization/api-authorization-query'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import type { Organization } from '@/types'
function getMatchingOrganization(
@@ -90,7 +89,7 @@ function usePrefillFormOnOrganizationsSuccess(
organizationsState: ReturnType<typeof useOrganizationsState>,
organization_slug: string | undefined
) {
- const prefillForm = useStaticEffectEvent(() => {
+ const prefillForm = useEffectEvent(() => {
if (organizationsState._tag === 'success') {
preselectOrganizationSlug({
form,
@@ -103,7 +102,8 @@ function usePrefillFormOnOrganizationsSuccess(
if (organizationsState._tag === 'success') {
prefillForm()
}
- }, [organizationsState._tag, prefillForm])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [organizationsState._tag])
}
export interface ApiAuthorizationValidScreenProps {
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
index ec78442d8f3..472fe6ccf79 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
@@ -6,13 +6,13 @@ import {
useCallback,
useContext,
useEffect,
+ useEffectEvent,
useMemo,
useState,
type PropsWithChildren,
} from 'react'
import { useFeaturePreviews } from './useFeaturePreviews'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { EMPTY_OBJ } from '@/lib/void'
type FeaturePreviewContextType = {
@@ -35,7 +35,7 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren) =
featurePreviews.reduce((a, b) => ({ ...a, [b.key]: false }), {})
)
- const initializeFlags = useStaticEffectEvent(() => {
+ const initializeFlags = useEffectEvent(() => {
setFlags(
featurePreviews.reduce((a, b) => {
const defaultOptIn = b.isDefaultOptIn
@@ -56,7 +56,8 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren) =
if (typeof window !== 'undefined') {
initializeFlags()
}
- }, [hasLoaded, initializeFlags])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [hasLoaded])
const value = {
flags,
diff --git a/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx b/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
index 4f35761afe3..1a090036cbf 100644
--- a/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
+++ b/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
@@ -4,7 +4,7 @@ import { useParams } from 'common'
import { Check } from 'lucide-react'
import { useTheme } from 'next-themes'
import { useQueryState } from 'nuqs'
-import { useEffect, useId, useMemo, useState } from 'react'
+import { useCallback, useEffect, useId, useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
import ReactMarkdown from 'react-markdown'
import { toast } from 'sonner'
@@ -36,7 +36,6 @@ import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useHasEntitlementAccess } from '@/hooks/misc/useCheckEntitlements'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { BASE_PATH } from '@/lib/constants'
interface ProviderFormProps {
@@ -84,7 +83,7 @@ export const ProviderForm = ({ config, provider, isActive }: ProviderFormProps)
const hasEntitlementAccess = useHasEntitlementAccess()
- const getValuesForProvider = useStaticEffectEvent(
+ const getValuesForProvider = useCallback(
(config: components['schemas']['GoTrueConfigResponse']) => {
const values: { [x: string]: string | boolean } = {}
Object.keys(provider.properties).forEach((key) => {
@@ -112,7 +111,8 @@ export const ProviderForm = ({ config, provider, isActive }: ProviderFormProps)
}
})
return values
- }
+ },
+ [provider]
)
const INITIAL_VALUES = useMemo(() => {
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
index 8f35b023f72..fccdb111fe6 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
@@ -48,9 +48,9 @@ import { useDatabasePolicyUpdateMutation } from '@/data/database-policies/databa
import { databasePoliciesKeys } from '@/data/database-policies/keys'
import { QueryResponseError, useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import useLatest from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
interface PolicyEditorPanelProps {
visible: boolean
@@ -259,7 +259,7 @@ export const PolicyEditorPanel = memo(function ({
}
}
- const resetState = useStaticEffectEvent(() => {
+ const resetStateRef = useLatest(() => {
if (!visible) {
editorOneRef.current?.setValue('')
editorTwoRef.current?.setValue('')
@@ -308,7 +308,9 @@ export const PolicyEditorPanel = memo(function ({
})
// when the panel is closed, reset all values
- useEffect(resetState, [visible, resetState])
+ useEffect(() => {
+ resetStateRef.current()
+ }, [visible, resetStateRef])
// whenever the deps (current policy details, new error or error panel opens) change, recalculate
// the height of the editor
diff --git a/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx b/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx
index 8c17aac26c7..28378ebba23 100644
--- a/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx
@@ -8,13 +8,12 @@ import {
useReactFlow,
} from '@xyflow/react'
import { ArrowLeft, ArrowRight } from 'lucide-react'
-import { memo, useState } from 'react'
+import { memo, useCallback, useState } from 'react'
import { Badge, cn } from 'ui'
import { useSchemaGraphContext } from './SchemaGraphContext'
import { EdgeData } from './Schemas.constants'
import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
const DefaultEdgeComponent = ({
id,
@@ -96,7 +95,7 @@ const EdgeRelationInfo = ({
const [show, setShow] = useState(false)
const reactFlowInstance = useReactFlow()
- const checkIfShouldBeDisplayed = useStaticEffectEvent(
+ const checkIfShouldBeDisplayed = useCallback(
(relationInfoElement: HTMLDivElement | null) => {
if (!relationInfoElement) return
const sourceNode = reactFlowInstance.getNode(source)
@@ -133,7 +132,8 @@ const EdgeRelationInfo = ({
// If it is, hide it as they are too close
setShow(!isNodeIntersectingWithSource && !isNodeIntersectingWithTarget)
- }
+ },
+ [reactFlowInstance, source, target]
)
return (
diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
index 1632d7323a9..e15a05f61ef 100644
--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
@@ -14,7 +14,7 @@ import {
import { Check, ChevronDown, Copy, Download, Loader2, Plus } from 'lucide-react'
import { useTheme } from 'next-themes'
import Link from 'next/link'
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import '@xyflow/react/dist/style.css'
@@ -62,7 +62,6 @@ import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { tablesToSQL } from '@/lib/helpers'
import type { SafePostgresTable } from '@/lib/postgres-types'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
@@ -165,7 +164,7 @@ export const SchemaGraph = () => {
saveNodePositions()
}
- const saveNodePositions = useStaticEffectEvent(() => {
+ const saveNodePositions = useCallback(() => {
if (schema === undefined) return console.error('Schema is required')
const nodes = reactFlowInstance.getNodes()
@@ -175,10 +174,10 @@ export const SchemaGraph = () => {
}, {})
setStoredPositions(nodesPositionData)
}
- })
+ }, [schema, reactFlowInstance, setStoredPositions])
const [selectedEdge, setSelectedEdge] = useState<Edge | undefined>(undefined)
- const handleSelectionChange = useStaticEffectEvent(
+ const handleSelectionChange = useCallback(
(params: OnSelectionChangeParams<Node<TableNodeData>, Edge<EdgeData>>) => {
if (params.edges.length === 1) {
setSelectedEdge(params.edges[0])
@@ -198,7 +197,8 @@ export const SchemaGraph = () => {
return { ...edge, animated: shouldAnimate }
})
if (hasChanges) reactFlowInstance.setEdges(nextEdges)
- }
+ },
+ [reactFlowInstance, setSelectedEdge]
)
const downloadImage = async (format: 'png' | 'svg') => {
diff --git a/apps/studio/components/interfaces/Database/Schemas/useExportSchemaToImage.ts b/apps/studio/components/interfaces/Database/Schemas/useExportSchemaToImage.ts
index 4145805b218..c5a146a5c81 100644
--- a/apps/studio/components/interfaces/Database/Schemas/useExportSchemaToImage.ts
+++ b/apps/studio/components/interfaces/Database/Schemas/useExportSchemaToImage.ts
@@ -1,16 +1,14 @@
import { toPng, toSvg } from 'html-to-image'
-import { useMemo, useState } from 'react'
+import { useCallback, useMemo, useState } from 'react'
import { toast } from 'sonner'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
-
export const useExportSchemaToImage = () => {
const [isDownloading, setIsDownloading] = useState(false)
// By doing this once and passing the result to html-to-image options, we avoid html-to-image calculating it for every node.
// This improves performance a lot. See https://github.com/bubkoo/html-to-image/issues/542#issuecomment-3249408793
const allPropertyNames = useMemo(() => getAllPropertyNames(), [])
- const exportSchemaToImage = useStaticEffectEvent(
+ const exportSchemaToImage = useCallback(
async ({
element,
projectRef,
@@ -64,7 +62,8 @@ export const useExportSchemaToImage = () => {
} finally {
setIsDownloading(false)
}
- }
+ },
+ [allPropertyNames]
)
return useMemo(
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
index ef8479914d9..59a65fc5b23 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
@@ -5,7 +5,7 @@ import { StudioPricingSidePanelOpenedEvent } from 'common/telemetry-constants'
import { isArray } from 'lodash'
import { Check, ExternalLink } from 'lucide-react'
import { useRouter } from 'next/router'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react'
import { plans as subscriptionsPlans } from 'shared-data/plans'
import { Button, cn, SidePanel } from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
@@ -32,7 +32,6 @@ import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-q
import type { OrgPlan } from '@/data/subscriptions/types'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { MANAGED_BY } from '@/lib/constants/infrastructure'
import { formatCurrency } from '@/lib/helpers'
import { useTrack } from '@/lib/telemetry/track'
@@ -151,7 +150,7 @@ export const PlanUpdateSidePanel = () => {
// this data from the organization query
orgProjects.filter((it) => it.status !== 'INACTIVE' && it.status !== 'GOING_DOWN').length > 0
- const onPanelOpened = useStaticEffectEvent(
+ const onPanelOpened = useEffectEvent(
(properties: StudioPricingSidePanelOpenedEvent['properties']) => {
track('studio_pricing_side_panel_opened', properties)
}
diff --git a/apps/studio/components/interfaces/Organization/SSO/SSOConfig.tsx b/apps/studio/components/interfaces/Organization/SSO/SSOConfig.tsx
index 1518e048588..152e46b3e03 100644
--- a/apps/studio/components/interfaces/Organization/SSO/SSOConfig.tsx
+++ b/apps/studio/components/interfaces/Organization/SSO/SSOConfig.tsx
@@ -1,6 +1,6 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { Trash } from 'lucide-react'
-import { useEffect, useState } from 'react'
+import { useEffect, useEffectEvent, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { Button, Card, CardContent, CardFooter, Form, FormControl, FormField, Switch } from 'ui'
@@ -25,7 +25,6 @@ import { useOrgSSOConfigQuery } from '@/data/sso/sso-config-query'
import { useSSOConfigUpdateMutation } from '@/data/sso/sso-config-update-mutation'
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { DOCS_URL } from '@/lib/constants'
const FormSchema = z
@@ -187,7 +186,7 @@ export const SSOConfig = () => {
deleteSSOConfig({ slug: organization.slug })
}
- const syncFormFromConfig = useStaticEffectEvent(() => {
+ const syncFormFromConfig = useEffectEvent(() => {
if (!organization?.slug) return
// Only reset form if it's not dirty (user hasn't made changes)
@@ -214,10 +213,11 @@ export const SSOConfig = () => {
useEffect(() => {
syncFormFromConfig()
- }, [ssoConfig, organization?.slug, syncFormFromConfig])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [ssoConfig, organization?.slug])
// Automatically add an empty domain field when SP-initiated is enabled
- const ensureDomainField = useStaticEffectEvent(() => {
+ const ensureDomainField = useEffectEvent(() => {
const currentDomains = form.getValues('domains')
if (enableSpInitiated && (!currentDomains || currentDomains.length === 0)) {
form.setValue('domains', [{ value: '' }], { shouldValidate: false })
@@ -226,7 +226,8 @@ export const SSOConfig = () => {
useEffect(() => {
ensureDomainField()
- }, [enableSpInitiated, ensureDomainField])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [enableSpInitiated])
return (
<ScaffoldContainer size="small" className="px-6 xl:px-10">
diff --git a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx
index bd13be6236d..e0b304f71f6 100644
--- a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx
+++ b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx
@@ -1,5 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { Dispatch, SetStateAction, useEffect, useRef } from 'react'
+import { Dispatch, SetStateAction, useEffect, useEffectEvent, useRef } from 'react'
import { toast } from 'sonner'
import { RealtimeConfig } from './useRealtimeMessages'
@@ -8,7 +8,6 @@ import { getKeys, useAPIKeysQuery } from '@/data/api-keys/api-keys-query'
import { getTemporaryAPIKey } from '@/data/api-keys/temp-api-keys-query'
import { useProjectPostgrestConfigQuery } from '@/data/config/project-postgrest-config-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { IS_PLATFORM } from '@/lib/constants'
import { getRoleImpersonationJWT } from '@/lib/role-impersonation'
import { useTrack } from '@/lib/telemetry/track'
@@ -40,7 +39,7 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
const jwtSecret = postgrestConfig?.jwt_secret
const track = useTrack()
- const onRoleUpdated = useStaticEffectEvent(() => {
+ const onRoleUpdated = useEffectEvent(() => {
track('realtime_inspector_database_role_updated')
})
diff --git a/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.tsx b/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.tsx
index 3f6ba8d0e66..1ee28fc0afb 100644
--- a/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.tsx
+++ b/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.tsx
@@ -1,7 +1,7 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
-import { useCallback, useEffect, useReducer } from 'react'
+import { useCallback, useEffect, useEffectEvent, useReducer } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { Card } from 'ui'
@@ -20,7 +20,6 @@ import { useProjectPostgrestConfigUpdateMutation } from '@/data/config/project-p
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useIsDataApiEnabled } from '@/hooks/misc/useIsDataApiEnabled'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
export const DataApiEnableSwitch = () => {
const { ref: projectRef } = useParams()
@@ -55,14 +54,15 @@ export const DataApiEnableSwitch = () => {
},
})
- const syncForm = useStaticEffectEvent(() => {
+ const syncForm = useEffectEvent(() => {
if (!isEnabledCheckPending) {
form.reset({ enableDataApi: isEnabled })
}
})
useEffect(() => {
syncForm()
- }, [syncForm, isEnabled])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [isEnabled])
const doUpdate = useCallback(
(enableDataApi: boolean) => {
diff --git a/apps/studio/components/interfaces/Settings/API/DataApiProjectUrlCard.tsx b/apps/studio/components/interfaces/Settings/API/DataApiProjectUrlCard.tsx
index 5f12b13bb54..887c5fd1bf5 100644
--- a/apps/studio/components/interfaces/Settings/API/DataApiProjectUrlCard.tsx
+++ b/apps/studio/components/interfaces/Settings/API/DataApiProjectUrlCard.tsx
@@ -1,7 +1,7 @@
import { useParams } from 'common'
import { AlertCircle } from 'lucide-react'
import { parseAsString, useQueryState } from 'nuqs'
-import { useEffect } from 'react'
+import { useEffect, useEffectEvent } from 'react'
import { Alert, AlertTitle } from 'ui'
import {
PageSection,
@@ -21,7 +21,6 @@ import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useLoadBalancersQuery } from '@/data/read-replicas/load-balancers-query'
import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
export const DataApiProjectUrlCard = () => {
@@ -39,14 +38,15 @@ export const DataApiProjectUrlCard = () => {
} = useReadReplicasQuery({ projectRef })
const { data: loadBalancers } = useLoadBalancersQuery({ projectRef })
- const syncSelectedDb = useStaticEffectEvent(() => {
+ const syncSelectedDb = useEffectEvent(() => {
if (querySource && querySource !== state.selectedDatabaseId) {
state.setSelectedDatabaseId(querySource)
}
})
useEffect(() => {
syncSelectedDb()
- }, [syncSelectedDb, querySource, projectRef])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [querySource, projectRef])
const selectedDatabase = databases?.find((db) => db.identifier === state.selectedDatabaseId)
const loadBalancerSelected = state.selectedDatabaseId === 'load-balancer'
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
index ba04d4c3d66..34316d449f3 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
@@ -12,7 +12,7 @@ import { partition } from 'lodash'
import { ChevronDown, Globe2, Loader2, Network } from 'lucide-react'
import { useTheme } from 'next-themes'
import Link from 'next/link'
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useEffectEvent, useMemo, useState } from 'react'
import '@xyflow/react/dist/style.css'
@@ -51,7 +51,6 @@ import {
useIsOrioleDb,
useSelectedProjectQuery,
} from '@/hooks/misc/useSelectedProject'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { timeout } from '@/lib/helpers'
interface InstanceConfigurationUIProps {
@@ -247,14 +246,15 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationU
// Second pass: once React Flow has measured the nodes, re-run the layout so
// dagre uses real heights. Only `nodesInitialized` going true should trigger
// this — the first-pass effect above handles node/view changes.
- const runMeasuredLayout = useStaticEffectEvent(() => {
+ const runMeasuredLayout = useEffectEvent(() => {
if (nodesInitialized && nodes.length > 0 && view === 'flow') {
setReactFlow({ measured: true })
}
})
useEffect(() => {
runMeasuredLayout()
- }, [nodesInitialized, runMeasuredLayout])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [nodesInitialized])
return (
<div className={cn('nowheel', diagramOnly ? 'h-full' : 'border-y')}>
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
index 72288d4f102..0ff022f434e 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
@@ -1,7 +1,7 @@
import { useDebounce } from '@uidotdev/usehooks'
import { useParams } from 'common'
import { compact, get, isEmpty, uniqBy } from 'lodash'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react'
import { useSelectedBucket } from '../FilesBuckets/useSelectedBucket'
import { STORAGE_ROW_TYPES, STORAGE_VIEWS } from '../Storage.constants'
@@ -16,7 +16,6 @@ import { useStorageExplorerShortcuts } from './useStorageExplorerShortcuts'
import { useStoragePreference } from './useStoragePreference'
import { useProjectStorageConfigQuery } from '@/data/config/project-storage-config-query'
import type { Bucket } from '@/data/storage/buckets-query'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { IS_PLATFORM } from '@/lib/constants'
import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'
@@ -64,7 +63,7 @@ export const StorageExplorer = () => {
useStorageExplorerShortcuts({ onClearSearch: handleClearSearch })
- const fetchContents = useStaticEffectEvent(async (bucket: Bucket) => {
+ const fetchContents = useEffectEvent(async (bucket: Bucket) => {
if (view === STORAGE_VIEWS.LIST) {
const currentFolderIdx = openedFolders.length - 1
const currentFolder = openedFolders[currentFolderIdx]
@@ -102,7 +101,8 @@ export const StorageExplorer = () => {
useEffect(() => {
if (bucket && projectRef) fetchContents(bucket)
- }, [bucket, projectRef, debouncedSearchString, selectedBucket.id, fetchContents])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [bucket, projectRef, debouncedSearchString, selectedBucket.id])
/** Checkbox selection methods */
/** [Joshen] We'll only support checkbox selection for files ONLY */
diff --git a/apps/studio/components/interfaces/Storage/StoragePolicies/StoragePoliciesBucketsSection.tsx b/apps/studio/components/interfaces/Storage/StoragePolicies/StoragePoliciesBucketsSection.tsx
index 477c384f635..fd54cd1a8b9 100644
--- a/apps/studio/components/interfaces/Storage/StoragePolicies/StoragePoliciesBucketsSection.tsx
+++ b/apps/studio/components/interfaces/Storage/StoragePolicies/StoragePoliciesBucketsSection.tsx
@@ -1,6 +1,13 @@
import { useVirtualizer } from '@tanstack/react-virtual'
import { ChevronUp, Search, X } from 'lucide-react'
-import { forwardRef, useEffect, useState, type HTMLAttributes, type ReactNode } from 'react'
+import {
+ forwardRef,
+ useEffect,
+ useEffectEvent,
+ useState,
+ type HTMLAttributes,
+ type ReactNode,
+} from 'react'
import { Button, cn, Collapsible, CollapsibleContent, CollapsibleTrigger } from 'ui'
import { ShimmeringLoader } from 'ui-patterns'
import { Input } from 'ui-patterns/DataInputs/Input'
@@ -19,7 +26,6 @@ import type { Policy } from '@/components/interfaces/Auth/Policies/PolicyTableRo
import { useMainScrollContainer } from '@/components/layouts/MainScrollContainerContext'
import { NoSearchResults } from '@/components/ui/NoSearchResults'
import { type Bucket } from '@/data/storage/buckets-query'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
export type SelectBucketPolicyForAction = {
addPolicy: (bucketName?: string, table?: string) => void
@@ -151,12 +157,15 @@ const BucketsPoliciesVirtualizedList = ({
const virtualItems = virtualizer.getVirtualItems()
const lastItem = virtualItems[virtualItems.length - 1]
- const fetchNext = useStaticEffectEvent(() => {
+ const fetchNext = useEffectEvent(() => {
if (lastItem && lastItem.index >= items.length - 1 && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
})
- useEffect(fetchNext, [lastItem, fetchNext])
+ useEffect(() => {
+ fetchNext()
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [lastItem])
return (
<div
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/useSpreadsheetImport.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/useSpreadsheetImport.ts
index 70243b17d90..0aaa35a8971 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/useSpreadsheetImport.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/useSpreadsheetImport.ts
@@ -1,10 +1,10 @@
import { debounce, noop } from 'lodash'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import type { SpreadsheetData } from './SpreadsheetImport.types'
import { parseSpreadsheet, parseSpreadsheetText } from './SpreadsheetImport.utils'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
+import useLatest from '@/hooks/misc/useLatest'
import { useTableEditorStateSnapshot } from '@/state/table-editor'
interface NoFileState {
@@ -212,32 +212,38 @@ export function useSpreadsheetImport({
},
[resetAbortController]
)
- const processTextStable = useStaticEffectEvent(processText)
+ const processTextRef = useLatest(processText)
const processTextDebounced = useMemo(
- () => debounce(processTextStable, debounceDuration),
- [debounceDuration, processTextStable]
+ () =>
+ debounce(
+ (...args: Parameters<typeof processText>) => processTextRef.current(...args),
+ debounceDuration
+ ),
+ [debounceDuration, processTextRef]
)
- const cleanup = useStaticEffectEvent(function cleanup() {
+ const cleanup = useEffectEvent(function cleanup() {
processTextDebounced.cancel()
abortControllerRef.current.abort()
})
useEffect(() => {
return cleanup
- }, [cleanup])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [])
// When the component mounts with a file already in global state (e.g. dropped onto the
// grid), the useState initializer above sets _tag to 'parsing_file' but does not start
- // the actual parse. Kick it off here. useStaticEffectEvent ensures we always read the
+ // the actual parse. Kick it off here. useEffectEvent ensures we always read the
// latest state/treatEmptyAsNull without re-triggering the effect.
- const processOnMount = useStaticEffectEvent(async function processOnMount() {
+ const processOnMount = useEffectEvent(async function processOnMount() {
if (state._tag === 'parsing_file') {
await processFile(state.file, { emptyStringAsNullHeaders: undefined })
}
})
useEffect(() => {
processOnMount()
- }, [processOnMount])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [])
const processSpreadsheet = useCallback(
async function processSpreadsheet({
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx
index 021609696de..eb0ad4ae99e 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx
@@ -2,7 +2,9 @@ import { useQuery } from '@tanstack/react-query'
import { ExternalLink } from 'lucide-react'
import Link from 'next/link'
import {
+ useCallback,
useEffect,
+ useEffectEvent,
useRef,
useState,
type Dispatch,
@@ -23,7 +25,6 @@ import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import { useIsSchemaExposed } from '@/hooks/misc/useIsSchemaExposed'
import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import {
checkDataApiPrivilegesNonEmpty,
DEFAULT_DATA_API_PRIVILEGES,
@@ -157,24 +158,26 @@ const useTableApiAccessHandler = (
const hasLoadedInitialData = useRef(false)
- const resetState = useStaticEffectEvent(() => {
+ const resetState = useEffectEvent(() => {
hasLoadedInitialData.current = !shouldReadExistingGrants
setPrivileges(defaultPrivilegesForNewTable)
})
useEffect(() => {
resetState()
- }, [params.type, selectedSchema, permissionsTemplateSchema, permissionsTemplateTable, resetState])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [params.type, selectedSchema, permissionsTemplateSchema, permissionsTemplateTable])
- const syncDefaultPrivileges = useStaticEffectEvent(() => {
+ const syncDefaultPrivileges = useEffectEvent(() => {
if (!isNewTable) return
if (!defaultPrivilegesQuery.isSuccess) return
setPrivileges(defaultPrivilegesForNewTable)
})
useEffect(() => {
syncDefaultPrivileges()
- }, [defaultPrivilegesQuery.status, syncDefaultPrivileges])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [defaultPrivilegesQuery.status])
- const syncApiPrivileges = useStaticEffectEvent(() => {
+ const syncApiPrivileges = useEffectEvent(() => {
if (hasLoadedInitialData.current) return
if (!apiAccessStatus.isSuccess) return
if (!privilegesForTable) return
@@ -192,7 +195,8 @@ const useTableApiAccessHandler = (
})
useEffect(() => {
syncApiPrivileges()
- }, [apiAccessStatus.status, syncApiPrivileges])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [apiAccessStatus.status])
const isPending =
!enabled ||
@@ -246,17 +250,17 @@ export const useTableApiAccessHandlerWithHistory = (
const privileges = innerResult.data?.schemaExposed ? innerResult.data.privileges : undefined
const previous = usePreviousDistinct(privileges)
- const clearAllPrivileges = useStaticEffectEvent(() => {
+ const clearAllPrivileges = useCallback(() => {
if (!innerResult.isSuccess) return
if (!innerResult.data.schemaExposed) return
innerResult.data?.setPrivileges(EMPTY_DATA_API_PRIVILEGES)
- })
+ }, [innerResult])
- const restorePreviousPrivileges = useStaticEffectEvent(() => {
+ const restorePreviousPrivileges = useCallback(() => {
if (!innerResult.isSuccess) return
if (!innerResult.data.schemaExposed) return
innerResult.data?.setPrivileges(previous ?? DEFAULT_DATA_API_PRIVILEGES)
- })
+ }, [innerResult, previous])
if (!innerResult.isSuccess) {
return innerResult
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
index bfcf2ed626e..49c3a09e7ad 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
@@ -1,5 +1,5 @@
import { LoaderCircle, Search } from 'lucide-react'
-import { useEffect, useState } from 'react'
+import { useEffect, useEffectEvent, useState } from 'react'
import { FilterBar, FilterCondition, type FilterGroup, type FilterProperty } from 'ui-patterns'
import {
@@ -8,7 +8,6 @@ import {
type LogsFilterOperator,
} from '../UnifiedLogs.filters'
import { useDataTable } from '@/components/ui/DataTable/providers/DataTableProvider'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
const buildFilterGroup = (
columnFilters: { id: string; value: unknown }[],
@@ -63,7 +62,7 @@ export const LogsFilterBar = () => {
)
// Read latest filterProperties without making the effect depend on its (per-render) identity.
- const syncFromColumnFilters = useStaticEffectEvent(() => {
+ const syncFromColumnFilters = useEffectEvent(() => {
setFilters(buildFilterGroup(columnFilters, new Set(filterProperties.map((p) => p.name))))
})
@@ -109,7 +108,8 @@ export const LogsFilterBar = () => {
useEffect(() => {
syncFromColumnFilters()
- }, [columnFilters, syncFromColumnFilters])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [columnFilters])
return (
<FilterBar
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx
index 981e4115c91..e059682c89d 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx
@@ -2,14 +2,13 @@ import { LOCAL_STORAGE_KEYS } from 'common'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/router'
import { parseAsString, useQueryState } from 'nuqs'
-import { useEffect, type PropsWithChildren } from 'react'
+import { useEffect, useEffectEvent, type PropsWithChildren } from 'react'
import { getSupportLinkQueryParams } from '@/components/ui/HelpPanel/HelpPanel.utils'
import useLatest from '@/hooks/misc/useLatest'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
@@ -84,7 +83,7 @@ export const LayoutSidebarProvider = ({ children }: PropsWithChildren) => {
sidebarManagerState.toggleSidebar(SIDEBAR_KEYS.EDITOR_PANEL)
)
- const onSidebarChanged = useStaticEffectEvent(
+ const onSidebarChanged = useEffectEvent(
(sidebarId: (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]) => {
track('sidebar_opened', { sidebar: sidebarId })
}
diff --git a/apps/studio/components/layouts/TableEditorLayout/ExportAllRows.tsx b/apps/studio/components/layouts/TableEditorLayout/ExportAllRows.tsx
index a3bbe44c604..259cfbb931d 100644
--- a/apps/studio/components/layouts/TableEditorLayout/ExportAllRows.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/ExportAllRows.tsx
@@ -30,7 +30,7 @@ import { tableEditorKeys } from '@/data/table-editor/keys'
import { getTableEditor, type TableEditorData } from '@/data/table-editor/table-editor-query'
import { isTableLike } from '@/data/table-editor/table-editor-types'
import { fetchAllTableRows } from '@/data/table-rows/table-rows-query'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
+import useLatest from '@/hooks/misc/useLatest'
import { DOCS_URL } from '@/lib/constants'
import type { RoleImpersonationState } from '@/lib/role-impersonation'
@@ -283,7 +283,7 @@ export const useExportAllRowsGeneric = (
const [confirmationMessage, setConfirmationMessage] = useState<string | null>(null)
- const exportInternal = useStaticEffectEvent(
+ const exportInternalRef = useLatest(
async ({ bypassConfirmation }: { bypassConfirmation: boolean }): Promise<void> => {
if (!params.enabled) return
@@ -383,6 +383,11 @@ export const useExportAllRowsGeneric = (
}
)
+ const exportInternal = useCallback(
+ (args: { bypassConfirmation: boolean }) => exportInternalRef.current(args),
+ [exportInternalRef]
+ )
+
const exportInDesiredFormat = useCallback(
() => exportInternal({ bypassConfirmation: false }),
[exportInternal]
diff --git a/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts b/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts
index 8cd101bf063..c80ac3fb2fd 100644
--- a/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts
+++ b/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts
@@ -1,7 +1,6 @@
import { useRouter } from 'next/router'
-import { useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useState } from 'react'
-import { useStaticEffectEvent } from '../useStaticEffectEvent'
import { BASE_PATH } from '@/lib/constants'
interface UsePreventNavigationOnUnsavedChangesOptions {
@@ -65,11 +64,11 @@ export const usePreventNavigationOnUnsavedChanges = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [confirmNavigate, hasChanges])
- const handleCancel = useStaticEffectEvent(() => {
+ const handleCancel = useCallback(() => {
setNavigateUrl(undefined)
- })
+ }, [])
- const handleConfirm = useStaticEffectEvent(() => {
+ const handleConfirm = useCallback(() => {
setConfirmNavigate(true)
let urlToNavigate = navigateUrl ?? '/'
if (BASE_PATH && urlToNavigate.startsWith(BASE_PATH)) {
@@ -78,7 +77,7 @@ export const usePreventNavigationOnUnsavedChanges = ({
if (!urlToNavigate.startsWith('/')) urlToNavigate = `/${urlToNavigate}`
setNavigateUrl(undefined)
router.push(urlToNavigate)
- })
+ }, [navigateUrl, router])
return useMemo(
() => ({
diff --git a/apps/studio/hooks/useStaticEffectEvent.ts b/apps/studio/hooks/useStaticEffectEvent.ts
deleted file mode 100644
index 5fe642be75c..00000000000
--- a/apps/studio/hooks/useStaticEffectEvent.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { useCallback, useLayoutEffect, useRef } from 'react'
-
-export const useStaticEffectEvent = <Callback extends Function>(callback: Callback) => {
- const callbackRef = useRef(callback)
-
- useLayoutEffect(() => {
- callbackRef.current = callback
- })
-
- const eventFn = useCallback((...args: any) => {
- return callbackRef.current(...args)
- }, [])
-
- return eventFn as unknown as Callback
-}
diff --git a/apps/studio/pages/cli/login.tsx b/apps/studio/pages/cli/login.tsx
index e87e1885478..3d435f20225 100644
--- a/apps/studio/pages/cli/login.tsx
+++ b/apps/studio/pages/cli/login.tsx
@@ -3,7 +3,7 @@ import { Terminal } from 'lucide-react'
import Head from 'next/head'
import Link from 'next/link'
import { useRouter } from 'next/router'
-import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from 'react'
import { Button, Card, CardContent } from 'ui'
import { Admonition, ShimmeringLoader } from 'ui-patterns'
@@ -18,7 +18,6 @@ import CopyButton from '@/components/ui/CopyButton'
import { InlineLink } from '@/components/ui/InlineLink'
import { createCliLoginSession } from '@/data/cli/login'
import { withAuth } from '@/hooks/misc/withAuth'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { buildStudioPageTitle } from '@/lib/page-title'
import { useProfile } from '@/lib/profile'
import type { NextPageWithLayout } from '@/types'
@@ -115,7 +114,7 @@ export const CliLoginScreen = ({
const startedForSessionIdRef = useRef<string | undefined>(undefined)
// Keep navigate in a ref so changing the prop never re-triggers the effect
// or cancels an in-flight POST via the isActive cleanup.
- const navigate = useStaticEffectEvent(navigateProp)
+ const navigate = useEffectEvent(navigateProp)
const displayName = profile?.primary_email ?? profile?.username
useEffect(() => {
@@ -167,7 +166,8 @@ export const CliLoginScreen = ({
return () => {
isActive = false
}
- }, [deviceCode, isLoggedIn, publicKey, routerReady, sessionId, tokenName, navigate])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [deviceCode, isLoggedIn, publicKey, routerReady, sessionId, tokenName])
if (status._tag === 'loading') {
return (
diff --git a/apps/studio/pages/sign-in-mfa.tsx b/apps/studio/pages/sign-in-mfa.tsx
index 8a68bfad43c..06187c031b4 100644
--- a/apps/studio/pages/sign-in-mfa.tsx
+++ b/apps/studio/pages/sign-in-mfa.tsx
@@ -2,7 +2,7 @@ import * as Sentry from '@sentry/nextjs'
import { useQueryClient } from '@tanstack/react-query'
import { getAccessToken, useParams } from 'common'
import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
+import { useEffect, useEffectEvent, useState } from 'react'
import { toast } from 'sonner'
import { LogoLoader } from 'ui'
@@ -10,7 +10,6 @@ import { SignInMfaForm } from '@/components/interfaces/SignIn/SignInMfaForm'
import SignInLayout from '@/components/layouts/SignInLayout/SignInLayout'
import { useAddLoginEvent } from '@/data/misc/audit-login-mutation'
import useLatest from '@/hooks/misc/useLatest'
-import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { auth, buildPathWithParams, getReturnToPath } from '@/lib/gotrue'
import { useTrack } from '@/lib/telemetry/track'
import type { NextPageWithLayout } from '@/types'
@@ -26,7 +25,7 @@ const SignInMfaPage: NextPageWithLayout = () => {
const signInMethodRef = useLatest(signInMethod)
const track = useTrack()
- const onSignInTracked = useStaticEffectEvent(() => {
+ const onSignInTracked = useEffectEvent(() => {
track('sign_in', {
category: 'account',
method: signInMethodRef.current,
diff --git a/apps/www/components/Legal/LegalDocVersions.tsx b/apps/www/components/Legal/LegalDocVersions.tsx
index adfaa743239..05a2655cabe 100644
--- a/apps/www/components/Legal/LegalDocVersions.tsx
+++ b/apps/www/components/Legal/LegalDocVersions.tsx
@@ -1,6 +1,5 @@
-import { useStaticEffectEvent } from '~/hooks/useStaticEffectEvent'
import { useRouter } from 'next/router'
-import { ComponentType, useEffect, useState } from 'react'
+import { ComponentType, useEffect, useEffectEvent, useState } from 'react'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from 'ui'
export type LegalDocVersion = {
@@ -19,7 +18,7 @@ const LegalDocVersions = ({ versions }: Props) => {
const latest = versions[0]
const [activeId, setActiveId] = useState<string>(latest.id)
- const syncActiveVersion = useStaticEffectEvent(() => {
+ const syncActiveVersion = useEffectEvent(() => {
const fromQuery = typeof router.query.version === 'string' ? router.query.version : undefined
if (fromQuery && versions.some((v) => v.id === fromQuery)) {
setActiveId(fromQuery)
@@ -31,7 +30,8 @@ const LegalDocVersions = ({ versions }: Props) => {
useEffect(() => {
if (!router.isReady) return
syncActiveVersion()
- }, [router.isReady, router.query.version, syncActiveVersion])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useEffectEvent fn intentionally not a dep (eslint-plugin-react-hooks v5 doesn't recognize stable useEffectEvent yet)
+ }, [router.isReady, router.query.version])
const active = versions.find((v) => v.id === activeId) ?? latest
const ActiveComponent = active.Component
diff --git a/apps/www/hooks/useStaticEffectEvent.ts b/apps/www/hooks/useStaticEffectEvent.ts
deleted file mode 100644
index 5fe642be75c..00000000000
--- a/apps/www/hooks/useStaticEffectEvent.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { useCallback, useLayoutEffect, useRef } from 'react'
-
-export const useStaticEffectEvent = <Callback extends Function>(callback: Callback) => {
- const callbackRef = useRef(callback)
-
- useLayoutEffect(() => {
- callbackRef.current = callback
- })
-
- const eventFn = useCallback((...args: any) => {
- return callbackRef.current(...args)
- }, [])
-
- return eventFn as unknown as Callback
-}